unable to insert in a linked list - c

i am trying to insert an element in the given linked list but when i want to print it its showing infinite loop.In insert() call i am passing the address of the pointer whereas in display i am only passing the address stored in the pointer. help me plz
#include<stdio.h>
struct node{
int item;
node *ptr;
};
int insert(node **head, int data, int position)
{
int count=1;
node *temp=malloc(sizeof(struct node));
temp->item=data;
temp->ptr=NULL;
node *p,*q;
p=*head;
if(*head==NULL)
{
*head=temp;
}
if(position==1)
{
temp->item=*head;
*head=temp;
}
else{
while(p!=NULL&&count<position)
{
count++;
q=p;
p=p->ptr;
}
q->ptr=temp;
temp->ptr=p;
}
}
void display(node *temp)
{
while(temp!=NULL)
{
printf("the data is %d",temp->item);
temp=temp->ptr;
}
}
void main()
{
node *head=malloc(sizeof(struct node));
insert(&head,29,1);
display(head);
}

Its a C Program please categorize properly.
No use of any C++ modules in your code.
Going with C implementation -
I think the double pointer is not required in a simple insert into a linked list.
You can do is -
void insert(node *head, int data){
node *temp= malloc(sizeof(struct node));
temp->item = data;
temp->ptr= NULL;
if(head==NULL){ //empty list
head=temp;
}
else {
while(head->ptr!=NULL){ //traverse till end
head=head->ptr;
}
head->ptr=temp;
}
}
And from main function call as insert(head,value);

Related

Linked list in c returns negative number instead of adding node

Can someone explain to me why this code returns a random negative number instead of adding the node as it should? If the call to addnode is removed the main function works as it should so the problem lies with the addnode function. I don't think it's malloc that has the problem and I can't for the life of me figure out what is. Please help, I'm an amateur at c and I have a vague understanding of how pointers work so I guess something's wrong with my pointers. Here's the full code :
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int addNode(struct node **head, int value);
void printList(struct node **head);
int main()
{
int value;
struct node *head;
head=NULL;
//int isempty(struct node *head);
for(int i=0;i<10;i++)
{
printf("\nInsert node value :");
scanf("%d",&value);
addNode(&head,value);
}
printList(&head);
return 0;
}
int addNode(struct node **head,int value)
{
struct node *newnode;
newnode=(struct node *) malloc(sizeof(struct node));
//if(newnode==NULL)
if(!newnode)
{
printf("Memory allocation error \n");
exit(0);
}
if(*head=NULL)
{
newnode->data=value;
newnode->next=NULL;
*head=newnode;
return 1;
}
else
{
struct node *current;
*current = **head;
while(current != NULL)
{
if(value<=(current->data)){
//περίπτωση 1ου κόμβου σε μη κενή λίστα
if(current==*head){
newnode->data=value;
newnode->next=*head;
*head=newnode;
return 1;
}
//περίπτωση ενδιάμεσου κόμβου
newnode->data=value;
return 1;
}
current = current->next;
}
}
}
/*int isempty(struct node *head){
return (head==NULL);
}*/
void printList(struct node **head) {
struct node *ptr = *head;
printf("\n[ ");
//start from the beginning
while(ptr != NULL) {
printf("(%d) ",ptr->data);
ptr = ptr->next;
}
printf(" ]");
return;
}
Well for starters you are having an assignment instead of a comparison in addNode
if(*head=NULL) should be if(*head==NULL)
Other than that, I think you are trying to maintain the elements in a sorted manner? But in any case you are manipulating pointers a bit more than you need to.

linked list: how to return the whole linked list after insterting

I am trying to return the head of a linked list in the function Insert of the following program. However, it is failing with compilation error.
Can anyone please tell me what wrong I have done:
#include<stdio.h>
#include<stdlib.h>
struct ListNode
{
int data;
struct ListNode *next;
};
int ListLength(struct ListNode *head)
{
int count = 0;
struct ListNode *temp=head;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
return count;
}
struct ListNode *Insert(struct ListNode *head, int value, int pos)
{
struct ListNode *temp,*curr;
curr=head;
int k=1;
temp=(struct ListNode *)malloc(sizeof(struct ListNode));
if(pos==1)
{
temp->data=value;
if(head==NULL)
{
temp->next=NULL;
head=temp;
}
else
{
temp->next=head;
head=temp;
}
}
else
{
while((curr!=NULL) && (k<pos))
{
k++;
curr=curr->next;
}
temp->data=value;
temp->next=curr->next;
curr->next=temp;
}
return head;
}
void printList(struct ListNode *head)
{
struct ListNode *temp;
temp=head;
while(temp!=NULL)
{
printf("%d",temp->data);
printf(" ");
temp=temp->next;
}
}
int main
{
struct ListNode *head=NULL;
//head = NULL;
head=Insert(head,10,1);
//Insert(head,11,2);
printList(head);
return 0;
}
I am trying to return the head of the new linked list after the insertion. I don't know where I am going wrong. Thanks in advance for the help.
(i) Firstly, include int main(void) as mentioned in the comments.
(ii) Next, with your current code, when you try printing the list, you are going to be in an infinite loop and get a stack overflow.
To avoid this, increment the temp to point to the next node after each print.
So your print function should look like:
void printList(struct ListNode *head)
{
struct ListNode *temp;
temp=head;
while(temp!=NULL)
{
printf("%d",temp->data);
printf(" ");
temp=temp->next; // this line is required
}
}
(iii) And in your main function, call the printList with an argument, that is the head of the node like this:
printList(head);
(iv) And don't forget to return the count in your finding the length of the list function. Add the return statement at the end of your ListLength function:
return count;
(v) Your current code does not handle a case when head is NULL, and user wants to insert at a position greater than 1. Or more generally, when a user wants to insert at a position that is greater than the current list's length.
While you trust such an input would not be given, always handle such exceptions (you would probably get a SEGMENTATION FAULT here when trying to access memory of null nodes).
To handle this, you can add a check at the start of the Insert function like,
int lenList = ListLength(head);
if (lenList < pos)
{
printf("Please provide a position less than %d to insert", lenList);
return 0; // don't proceed with inserting node with NULL pointers
}
If head is declared global you don't have to return it. (Sorry, my answer is short)

why this linked list code in c malfunction?

I have written this code in c to implement linked list. while the semantic and syntax are fine, it does not work as it should. For example, when I insert 1 into the list and then print the linked list, it shows that the list is empty.
#include<stdio.h>
#include<stdlib.h>
struct node {
int info;
struct node *next;
}; typedef struct node Node;
void addNode(Node *head, int x)
{
Node *temp;
temp=malloc(sizeof(temp));
temp->info=x;
if (head==NULL)//if this is the first node in the list
{
head=temp;
temp->next=NULL;
}
else //if not, add it as the head
{
temp->next=head;
head=temp;
}
}
void appendNode(Node *head, int x)
{
Node *rear =head;
Node *temp= malloc(sizeof(temp));
temp->info=x;
temp->next=NULL;
while (rear->next!=NULL)
rear=rear->next;
rear->next=temp;
rear=temp;
}
void insertNodeafter(Node *head, int location, int x)
{
int i;
Node *before, *after = head;
Node *temp= malloc(sizeof(temp));
temp->info=x;
for (i=0;i<location;i++)
before=before->next;
after=before->next;
temp->next=after;
before->next=temp;
}
void insert(Node *head, int x)
{
int c=0;
Node *temp;
temp=head;
if(temp==NULL)
{
addNode(temp,x);
}
else
{
while(temp!=NULL)
{
if(temp->info<x)
c++;
temp=temp->next;
}
if(c==0)
addNode(temp,x);
else if(c<listSize())
insertNodeafter(temp,x,++c);
else
appendNode(temp,x);
}
}
int listSize()
{
Node *head, *n;
int c=0;
n=head;
while(n!=NULL)
{
n=n->next;
c++;
}
return c;
}
void DisplayLinkedList(Node* head)
{
Node *rear=NULL;
if (head==NULL)
printf("list is empty!\n");
else
{
rear=head;
while (rear!=NULL)
printf("%d |---> ", rear->info);
rear=rear->next;
}
}
int getNextNode(Node *head)
{
if (head == NULL)
return -1;
else
return head->next->info;
}
Node* deleteNode(Node *head, int x)
{
Node *temp;
if (head == NULL)
return NULL;
else
{
if (head->info==x)
{
temp = head->next;
free(head);
head=temp;
return head;
}
else
{
deleteNode(head->next,x);
return head;
}
}
}
void main()
{
int i=0;
Node *myNode;
insert(myNode,1);
DisplayLinkedList(myNode);
}
Because you are using Node* variable instead of using Node** variable in function parameter. Since you are using Node* so changes done in variable head is local to that function. If you want to reflect these changes even after function call(which you obviously wants to) then use Node** and use it accordingly in your code.
As the previous poster has mentioned, it is best to use Node** variable to reflect changes after a function call. If you wanted to use Node*, you'd have to return Node* back to main to print from it.
I pared your code down to add the 1, using AddNode, insert and DisplayLinkedList and it is now displaying correctly with the code below.
You should also set Node* to NULL in main to initialize the empty linked list. Check your DisplayLinkedList function - you're missing curly brackets in the while loop. It was only reading the printf line and not traversing the list, leading to an infinite loop.
Best practice is to debug and test as you are creating this program.
#include<stdio.h>
#include<stdlib.h>
#include "stack.h"
void main()
{
int i=0;
Node *myNode;
myNode = NULL;
insert(&myNode,1);
DisplayLinkedList(myNode);
}
void addNode(Node **head, int x)
{
Node *temp;
temp=malloc(sizeof(temp));
temp->info=x;
if (*head==NULL)//if this is the first node in the list
{
*head=temp;
temp->next = NULL;
}
else //if not, add it as the head
{
temp->next=*head;
*head=temp;
}
}
void insert(Node **head, int x)
{
int c=0;
Node *temp;
temp=*head;
if(temp==NULL)
{
addNode(head ,x);
}
}
void DisplayLinkedList(Node* head)
{
Node *rear=NULL;
if (head==NULL)
printf("list is empty!\n");
else
{
rear=head;
while (rear!=NULL)
{
printf("%d |---> ", rear->info);
rear=rear->next;
}
}
}

how to insert into the singly linked list using double pointers?

codepad linkI'm trying to insert into a linked list using double pointers.but i don't understand where i'm going wrong i followed up other links on stack overflow,i even referred to couple of books so please help me.i kept code for insertion at position 1.In the output the previous insertion is lost.
struct node
{
int data;
node *next;
};
void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
if(pos==1)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->data=k;
newnode->next=*head;
*head=newnode;
}
}
void print(node **head)
{
printf("the elements are.. ");
while(*head!=NULL)
{
printf("%d ",(*head)->data);
(*head)=(*head)->next;
}
printf("\n");
}
int main()
{
insert(&head,5,1);
print(&head);
insert(&head,4,1);
print(&head);
return 0;
}
sorry for poor indentation.i'm beginner please help me.
Your print function is incorrect. You are erasing your head in line (*head)=(*head)->next;. Change function to
void print(node **head)
{
printf("the elements are.. ");
node *temp = *head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
You will receive following output:
the elements are.. 5
the elements are.. 4 5
Check this out.
struct node //Missed struct's name
{
int data;
node *next;
};
void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
if(pos==1)
{
node *newnode= new node();
newnode->data=k;
newnode->next=*head; //You called head which is not a member of node's struct
*head=newnode;
}
}
int main()
{
node *head=NULL;
insert(&head,5,1);
insert(&head,4,1);
}

What is wrong with my code for singly linked list?

I'm working on a singly linked list in C. This is what I've written so far.
C program
#include<stdio.h>
#include<stdlib.h>
struct Node{
int value;
struct Node *next;
};
struct Node* init()
{
struct Node* head=NULL;
head=malloc(sizeof(struct Node));
head->value=-1;
return head;
}
int length(struct Node* head)
{
struct Node* current=head;
int length=0;
while(current!=NULL)
{
length++;
current=current->next;
}
return length;
}
void print(struct Node* head)
{
int i=0;
int len=length(head);
for(i=0;i<len;i++)
{
printf("%d%d",i,head[i].value);
printf("\n");
}
}
struct Node* insert(int data,struct Node* head)
{
struct Node* current=NULL;
if(length(head) > 0)
{
int val=head->value;
if (val==-1)
{
head->value=data;
head->next=NULL;
}
else
{
current=malloc(sizeof(struct Node));
current->value=data;
current->next=head;
head=current;
}
}
else
{
printf("List is empty");
}
return head;
}
int main()
{
/* printf("Hello"); */
struct Node *head=init();
head=insert(20,head);
head=insert(30,head);
head=insert(40,head);
print(head);
printf("%d",length(head));
return 0;
}
The output values I get are:
Index Value
0 40
1 0
2 0
and for length is 3. I'm not able to grasp what I'm doing wrong here in pointer manipulation.
One obvious problem is not setting next to NULL on init - that would fail when checking length on the empty list
But your real problem is the print function
You can't use:
head[i].value
That notation is only valid for arrays, you need to use next to find each member
The Init function should set Next to NULL
struct Node* init()
{
struct Node* head=NULL;
head=malloc(sizeof(struct Node));
head->value=-1;
head->next=NULL;
return head;
}
otherwise the first call to length return an undefined result ( or GPF ).
Here:
for (i = 0; i < len; i++)
{
printf("%d%d", i, head[i].value);
printf("\n");
}
You need to advance from one node to another with head = head->next in the same manner as you do it in length(). head[i] won't do it.
It's unclear why your init() and insert() are so unnecessarily complicated and I don't even want to try to guess why. I want to suggest a better insert() and no init():
struct Node* insert(int data, struct Node* head)
{
struct Node* current;
current = malloc(sizeof(struct Node));
current->value = data;
current->next = head;
return current;
}
And then you do this:
int main(void)
{
struct Node *head = NULL;
head = insert(20, head);
head = insert(30, head);
head = insert(40, head);
print(head);
printf("%d", length(head));
return 0;
}
The notation head[i].value is only valid for arrays but not for linked lists. Arrays and linked lists are completely different, allocation of memory towards arrays is premeditated where as for linked lists it's dynamic. That is the reason why we use pointers for linked lists.
In init() you didn't assign null which causes the loop to run infinite times when you call length() for first time.
I am posting the modified code of print function:
void print(struct Node* head)
{
int i=0;
int len=0;
struct Node* current=head;
for(i=0;i<len;i++)
{
printf("%d %d",i,current->value);
print("\n");
current=current->next;
}
}

Resources