I'm getting assignment makes pointer from integer without a cast errors on lines 46 and 53, the two lines with double asterisks on either side, and for the life of me, I cannot figure out why. Linked lists are very new to me, I don't know how they work completely yet.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node_def
{
int data;
struct node_def *next;
};
typedef struct node_def node;
node *makeNode (int a);
node *insertFront(node *head,node *new);
void printList(node *head);
int numNodes = 0;
int main()
{
srand(time(0));
int r = rand() % 10000;
int i = 0;
node *head = NULL;
node *tmp = NULL;
printf("How many nodes? ", numNodes);
scanf("%d", numNodes);
printf("\n");
head = insertFront(head, tmp);
for(i = 0; i < numNodes; i++)
{
makeNode(r);
printList(head);
}
printf("\n");
return 0;
}
node *makeNode (int a)
{
node *new = malloc(sizeof(node));
**new = a;**
return new;
}
node *insertFront(node *head, node *new)
{
**new->data = head;**
new->next = new;
return 0;
}
void printList(node *head)
{
int j = 0;
for(j = 0; j < numNodes; ++j)
{
while (head != NULL)
{
printf(" %4d", head->data);
head = head->next;
}
if(j % 10 == 0)
printf("\n");
}
return;
}
new = a is meant to make new nodes and assign them a random number from 0 - 9999.
You try to assign r to new, but new is a struct.
You make a pointer to struct : node *new
What you want to do is assigning r to new->data, which is an int.
node *insertFront(node *head, node *new)
{
**new->data = head;** // ** is meaningless
new->next = new; // new is a reserved key word, don't use it this way
return 0;
}
What you try to do is to put a NULL pointer as the head of your list.
Just push element into it within your makeNode function.
insert like this :
void createNode(node *head)
{
Node *new_node = malloc(sizeof(Node*));
new_node->data = rand() % 100000;
new_node->next = NULL;
if(head == NULL)
head = new_node;
else if(head != NULL)
//Here you have to adapt your list, search (linked list crud functions)
}
You have a bad understanding about what pointers are.
Hope it helps bro
Related
I am a beginner to C and am learning linked lists. I tried making functions to have everything organised but no matter what i do the function print_list doesn't print the values. The output is only START and END. I noticed that if I put the same block of code directly into the function that builds the lists, then it prints correctly. What am I doing wrong? (Also first time asking on stack overflow)
Thank you to whoever answers.
#include <stdlib.h>
#include <stdio.h>
typedef struct nd
{
int val;
struct nd *next;
} node;
typedef node * Lista;
void print_list(node*currnode)
{
printf("START -> ");
while (currnode != NULL)
{
printf("%d -> ", currnode->val);
currnode = currnode->next;
}
printf("END");
}
//reimpilista means "buildlist"
node*riempilista(Lista lis){
node *currentNode, *temp;
int i,n;
printf("how many nodes?\n");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
currentNode = (node *)malloc(sizeof(node));
printf("Enter element %d : ", (i + 1));
scanf("%d", ¤tNode->val);
if (i == 0)
{
temp = currentNode;
}
else
{
temp->next = currentNode;
temp = currentNode;
}
}
temp->next = NULL;
return lis;
}
int main(){
Lista listautente=NULL;
listautente=riempilista(listautente);
print_list(listautente);
return 0;
}
When you build the list you need to return the head of the list as a result. So you need to store the pointer to the first node. Then when adding a new node you need to know the previous node, so you need to store it as well. The last added node should have next field poiting to NULL otherwise you won't be able to determine the end of the list and will get an exception.
Here is your code slightly edited.
#include <stdlib.h>
#include <stdio.h>
typedef struct nd {
int val;
struct nd *next;
} node;
typedef node *Lista;
void print_list(node *currnode) {
printf("START -> ");
while (currnode != NULL) {
printf("%d -> ", currnode->val);
currnode = currnode->next;
}
printf("END");
}
//reimpilista means "buildlist"
node *riempilista() {
node *firstNode = NULL, *currentNode = NULL, *previousNode = NULL;
int i, n;
printf("how many nodes?\n");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
currentNode = (node *)malloc(sizeof(node));
printf("Enter element %d : ", (i + 1));
scanf("%d", ¤tNode->val);
currentNode->next = NULL;
if (i == 0) {
firstNode = currentNode;
}
if (previousNode != NULL) {
previousNode->next = currentNode;
}
previousNode = currentNode;
}
return firstNode;
}
int main() {
Lista listautente = riempilista();
print_list(listautente);
return 0;
}
I tried to fix your program with minimal changes. Here it is:
Change
node *currentNode, *temp;
to
node *currentNode, *temp, *head;
Change
temp = currentNode;
to
temp = currentNode; head = temp;
Change
return lis;
to
return head;
Here is the link to the modified code:
https://onlinegdb.com/8cjqifgl2
I am trying to create a function that turns an array to a linked list for further usage
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode * create_linked_list(int *nums , int count)
{
ListNode * ptr = (ListNode*)malloc(count*sizeof(ListNode));
for (int i =0; i < count; i++)
{
ListNode new;
new.val = nums[i];
ptr[i] = new;
}
for (int j=0; j < count; j++)
{
if ( j>=count )
ptr[j].next = NULL;
else
ptr[j].next = &ptr[j+1];
}
return ptr;
}
int main()
{
int nums[] = {2,4,3};
ListNode *node_ptr = create_linked_list(nums , sizeof(nums)/sizeof(nums[0]));
ListNode start = node_ptr[0];
}
I have this simple function that turns an array of integers into a linked list, assume the last node in the list is called x_node now x_node.next is equal to NULL because it is defined inth the second for loop in create_linked_list, but when I try to add a while loop in the main it results in a segmentation fault
int main()
{
int nums[] = {2,4,3};
ListNode *node_ptr = create_linked_list(nums , sizeof(nums)/sizeof(nums[0]));
ListNode start = node_ptr[0];
while (start.next != NULL)
{
printf("%d \n", start.val);
start = *start.next; // at the last element it should stop but a segfault is thrown
}
}
If you wan t to loop over a linked list, you need to create the list properly in the first place. Your create_linked_list function is totally wrong.
You want this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
ListNode* create_linked_list(int* nums, int count)
{
ListNode* head = NULL;
ListNode *previous = NULL;
for (int i = 0; i < count; i++)
{
// create new node and put value into it
ListNode *new = malloc(sizeof(ListNode));
new->val = nums[i];
new->next = NULL;
if (i == 0) // head will point to the first element
head = new;
if (previous)
{
// if previous node exists, link to newly created node
previous->next = new;
}
previous = new; // new node becomes previous node
}
return head;
}
int main()
{
int nums[] = { 2,4,3 };
ListNode* head = create_linked_list(nums, sizeof(nums) / sizeof(nums[0]));
// now it's up to you to write the print_list function
// print_list(head);
}
Now writing the print_list function should be easy. Hint: take a pencil and a piece if paper and draw the nodes with arrows as pointers pointing to the next node.
Below is a Minimal Reproducible Example from my code. What I am doing is that I am inserting data in a list of structs and printing them on the console.
I want to print from each link only the first element that is inserted into each list of structs.
But how is that possible when instead of data in my struct I have:
typedef struct Node
{
int rollnumber, src, dst;
double gentime;
struct Node *next;
} Node;
(rollnumber, src, dst,gentime are the information I am reading from text files, but the reading code is not nessacary, so I wrote it with testdata.)
MINIMAL REPRODUCIBLE EXAMPLE
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct Node
{
int data;
struct Node* next;
} Node;
int push_front(Node** head, int data)
{
Node* new_node = malloc(sizeof(Node));
int success = new_node != NULL;
if (success)
{
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
return success;
}
void output(Node* head)
{
for (Node* current = head; current != NULL; current = current->next)
{
printf("%d ", current->data);
}
}
void display(Node** set, int i)
{
output(set[i]);
putchar('\n');
}
int main(void)
{
int testdata = 1;
Node* link[N] = { 0 };
struct Node* head = NULL;
for (int i = 0; i < N; i++) {
push_front(&link[i], testdata++);
push_front(&link[i], testdata++);
}
for (int i = 0; i < N; i++) {
printf("link[%d]:", i);
display(link, i);
}
}
If you only want to print the first element of each link list, just do not loop in output:
void output(Node* head)
{
printf("%d ", head->data);
}
If I am right you want the first element of the list right ??
If so than the way you are working you are pushing the new node in front of old node, so your first node is now the last in the line, so all you need to do is to iterate the list till Node* next == null, and that node will be your answer
Node *getLastInLine( Node *Head){
Node *ptr;
ptr = Head;
if( ptr == NULL) return NULL;
while(ptr-> next != NULL){
ptr = ptr->next;
}
return ptr;
}
I am trying to create a program to solve the classic problem of brackets balancing.
The program needs to tell the user if an the parantheses appearing in an expression are balanced.
I am very new to C/C++, coming from Python, so please excuse my ignorance and please point me towards the right direction!
What I have up until now is below. When compiled with gcc -o exec program.c then ./exec it outputs: List is: ) ( ] [ } { , rather than what I would expect: List is: { } [ ] ( )
I do not understand why, is there an obvious mistake?
I keep searching for it...
Also, I would be very grateful if you could comment if my logic on how I am designing those functions makes sense and is correct: I feel I actually need to put those pointer variables as arguments to the functions?
Thank you!
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Parantheses check:
struct Node {
char data;
struct Node* next;
};
struct Node* head_of_listofparans = NULL;
struct Node* head_of_listofparans_open = NULL;
struct Node* head_of_listofparans_close = NULL;
struct Node* insert_at_beginning(char c, struct Node* head) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = c;
temp->next = head;
head = temp;
return head;
}
void Delete(int n, struct Node* head) { // removes the n-th node (n=1 represents the head node, n=2 represents the second node)
struct Node* temp1 = head;
if (n==1) {
head = temp1->next;
free(temp1);
return;
}
int i;
for (i=0; i<n-2; i++) { // if n=2 (want to delete the 2nd node), this for-loop doesn't get executed.
temp1 = temp1->next;
} // temp1 now points to the n-1 th node. if n=2, temp1 still (correctly) points towards the head (first node)
struct Node* temp2 = temp1->next; // temp2 points towards the n-th node
temp1->next = temp2->next; // n-1 th node now points to the n+1 th node
free(temp2); // delete the n-th node
}
struct Node* createListOfParantheses(char* parants, struct Node* initial_head) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = parants[0];
temp->next = initial_head;
initial_head = temp; // 1st node created. the link of this node points to NULL now. head of the list points to this newly created 1st node.
int i;
for (i=1; i<=(int)strlen(parants); i++) {
initial_head = insert_at_beginning(parants[i], initial_head);
}
return initial_head;
}
// int ParanthesisCheck(char* parantheses_open, char* parantheses_close, char* expr) {
// int n = int(strlen(expr));
// int i;
// for (i=0; i<=n-1; i++) {
// if (strchr(parantheses_open, expr[i])!=NULL) { // if expr[i] can be found in "{[("
// insert_at_beginning(expr[i]) // ppush(expr[i]);
// }
// else if (strchr(parantheses_close, expr[i])!=NULL) { // if expr[i] can be found in "}])"
// if ((check_emptiness_of_stack()==1) || (get_top_of_stack() != expr[i])) { // || signifies the logical OR
// return 0;
// }
// else {
// Delete(1, head_of_stack); // ppop(), delete the very first node (head node), i.e. the most-recently-introduced node
// }
// }
// }
// return check_emptiness_of_stack()==1 ? 1:0;
// }
void Print_List_Of_Parans(struct Node* head) {
struct Node* temp = head;
printf("List is: ");
while (temp != NULL) {
printf(" %c", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
char paras[7] = "{}[]()";
char paras_open[4] = "{[(";
char paras_close[4] = "}])";
char input_expr[20] = "(a+b)";
// int j;
// for (j=0; j<7; j++) {
// scanf("%c", ¶s[j]); // ¶s[j] is equivalent to: paras + j if paras is an array
// printf("%s %d\n", "Iteration number: ", j);
// } // doesn't work because scanf reads 1 character, alright, but adds a \n at its end, so consumes 2 memory locations from the array char paras[7], not 1 as expected.
head_of_listofparans = createListOfParantheses(paras, head_of_listofparans);
head_of_listofparans_open = createListOfParantheses(paras_open, head_of_listofparans_open);
head_of_listofparans_close = createListOfParantheses(paras_close, head_of_listofparans_close);
Print_List_Of_Parans(head_of_listofparans);
// int result = ParanthesisCheck(head_of_listofparans_open, head_of_listofparans_close, input_expr);
// printf("%d\n", result);
return 0;
}
I am just implementing circular linked list program but in this program i am having to face trouble, as you can see I am going to past code below, when I call insertAtLast and isertAtFirst function it's work fine but as soon as I call viewList function to view list item but it shows "there is no items" which I wrote inside if block for run when last is null but in this program I have already inserted two items before viewList call so I think last should not be null because I have already inserted item, I want to print all items of list by viewList function
#include <stdio.h>
#include <stdlib.h>`
#include <conio.h>
struct node {
int item;
struct node *next;
};
void insertAtFirst(struct node **last, int data) {
struct node *n, *t;
n = malloc(sizeof(struct node));
n->item = data;
t = *last;
if(*last == NULL) {
n->next = n;
t = n;
}
else {
n->next = t->next;
t->next = n;
}
}
void insertAtLast(struct node **last, int data) {
struct node *n, *t;
n = malloc(sizeof(struct node));
n->item = data;
t = *last;
if(*last == NULL) {
n->next = n;
t = n;
}
else {
n->next = t->next;
t->next = n;
t = n;
}
}
void viewList(struct node *last) {
struct node *start;
if(last == NULL)
printf("\n there is no items......");
else {
start = last->next;
while(start->next != last->next) {
printf("%d ", start->item);
start = start->next;
}
}
}
int main(){
struct node *last = NULL;
insertAtLast(&last, 3);
insertAtFirst(&last, 5);
viewList(last);
return 0;
}
You should use *last = n instead of t = n.
And that's because the latter just causes the variable t to point to n and that's it. But by doing *last = n you will at least insert a value in the list even if last == NULL I guess that would give the desired output.