Linked list implementation in C? - c

The following code is a single linked list implementation in c. every time the function addtoqueue is being called, it creates a node and appends the node to the end of the list. The pointer list points to the first node of the linked list, but every time I update the value of node using input (the values are read from client connection), all the previous nodes in the linked list gets the last filename that has been inputed. i.e:
after 1st node creation (abc.txt as input): linked list has one node with value abc.txt;
after 2nd node (xyz.txt as input): linked list has two nodes with same filename xyz.txt.(instead of one node with abc and one node with xyz)
There's my implementation below, what end where is the logical failure?
struct listdata
{
char *filename;
struct listdata *next;
}*list;
void addtoqueue(int client,char *value)
{
char buffer[512];
char filepath[100];
struct listdata *temp,*input;
input=(struct listdata *)malloc(sizeof(struct listdata));
read(client,buffer,sizeof(buffer));
d = sscanf(buffer,"%s",filepath);
input->filename=&filepath;
if(list == NULL)
{
list=input;
list->next=NULL;
}
else if((list->next)==NULL)
{
list->next=input;
input->next=NULL;
}
else
{
temp=list->next;
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next=input;
input->next=NULL;
}
//list points to the first node
}

This is simpler
void addtoqueue(int client,char *value)
{
char buffer[512];
char filepath[100];
struct listdata *temp=NULL,*input=NULL;
input=(struct listdata *)malloc(sizeof(struct listdata));
read(client,buffer,sizeof(buffer));
d=sscanf(buffer,"%s",filepath);
input->filename=&filepath;
input->next = NULL;
if(list == NULL)
{
list=input;
}
else
{
temp=list;
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=input;
}
}

Here is the full code for linked list..
this will definately help you
visit http://codingloverlavi.blogspot.in/2013/12/singly-linked-list.html for more details
//Single LinkList
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node*next;
};
typedef struct Node Node;
Node*sort2(Node*,Node**);
Node*sort(Node*start,Node**);
Node*reverseList(Node*,Node**);
void insertAfter(Node*,Node**,int,int);
Node* insertBefore(Node*,int,int);
void printList(Node*);
Node*insertLast(Node*,Node**,Node*);
Node*createNode(int);
int search(Node*,int);
Node*Delete(Node*,Node**,int);
Node*deleteLast(Node*,Node**);
int main()
{
int temp,ch,num;
Node *newNode,*start,*last;
start=last=NULL;
while(1)
{
printf("\n_________________menu__________________\n");
printf("1. insert at the end of list...\n");
printf("2. print the list...\n");
printf("3. search a speific item...\n");
printf("4. insert after a specific node...\n");
printf("5. insert a node before a specific node...\n");
printf("6. delete a specific node...\n");
printf("7. delete a last node...\n");
printf("8. reverse the link list...\n");
printf("9. sort the link list...\n");
printf("10. sort the link list(another method)...\n");
printf("11. exit...\n");
printf("\nenter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter the data part of the node that you want to insert :\n");
scanf("%d",&temp);
newNode=createNode(temp);
start=insertLast(start,&last,newNode);
break;
case 2:
printList(start);
break;
case 3:
printf("enter the data that you want to search : ");
scanf("%d",&temp);
if(search(start,temp))
printf("the number you entered was in the list");
else
printf("the number you entered was not in the list");
break;
case 4:
printf("enter the data of the node after which you want to insert new node : ");
scanf("%d",&temp);
printf("enter the data part of the node that you want to insert : ");
scanf("%d",&num);
insertAfter(start,&last,temp,num);
break;
case 5:
printf("enter the data of the node before which you want to insert new node : ");
scanf("%d",&temp);
printf("enter the data part of the node that you want to insert : ");
scanf("%d",&num);
start=insertBefore(start,temp,num);
break;
case 6:
printf("enter the data part of the node that you want to delete : ");
scanf("%d",&temp);
start=Delete(start,&last,temp);
break;
case 7:
if(last==NULL)
{
printf("the list is empty...you can't delete any node...");
break;
}
start=deleteLast(start,&last);
break;
case 8:
start=reverseList(start,&last);
break;
case 9:
start=sort(start,&last);
break;
case 10:
start=sort2(start,&last);
break;
case 11:
exit(1);
default:
printf("you have entered a wrong choice...enter a valid choice");
}
}
}
Node* createNode(int data)
{
Node*newNode;
newNode=(Node*)malloc(sizeof(Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
Node*insertLast(Node*start,Node**p2last,Node*newNode)
{
if(*p2last==NULL)
{
*p2last=newNode;
return newNode;
}
(*p2last)->next=newNode;
*p2last=newNode;
return start;
}
void printList(Node*start)
{
printf("your list is as follows : \n");
while(start)
{
printf("%d\t",start->data);
start=start->next;
}
}
int search(Node*start,int data)
{
while(start)
{
if(start->data==data)
return 1;
start=start->next;
}
return 0;
}
void insertAfter(Node*start,Node**p2last,int data,int num)
{
Node*newNode,*tmp;
newNode=createNode(num);
if(*p2last==NULL)
printf("the list is empty...");
tmp=start;
while(tmp)
{
if(tmp->data==data)
break;
tmp=tmp->next;
}
if(!tmp)
printf("the number you enter was not in the list\n");
else
{
newNode->next=tmp->next;
tmp->next=newNode;
if(tmp==*p2last)
*p2last=newNode;
}
}
Node*insertBefore(Node*start,int data,int num)
{
Node *newNode,*prev,*tmp;
prev=NULL;
newNode=createNode(num);
if(start==NULL)
{
printf("the list is empty...");
return start;
}
tmp=start;
while(tmp)
{
if(tmp->data==data)
break;
prev=tmp;
tmp=tmp->next;
}
if(!tmp)
printf("the number you enter was not in the list\n");
else if(prev==NULL)
{
newNode->next=start;
start=newNode;
}
else
{
newNode->next=prev->next;
prev->next=newNode;
}
return start;
}
Node*Delete(Node*start,Node**p2last,int data)
{
Node*prev,*tmp;
tmp=start;
prev=NULL;
while(tmp)
{
if(tmp->data==data)
break;
prev=tmp;
tmp=tmp->next;
}
if(!tmp)
{
printf("the item you entered was not in the list...\n");
return start;
}
if(tmp==start)
{
if((*p2last)==start)
*p2last=NULL;
return NULL;
}
prev->next=tmp->next;
if(tmp==(*p2last))
*p2last=prev;
free(tmp);
return start;
}
Node*deleteLast(Node*start,Node**p2last)
{
return Delete(start,p2last,(*p2last)->data);
}
Node*reverseList(Node*start,Node**p2last)
{
Node*ptr,*tmp,*prev;
(*p2last)=start;
prev=NULL;
for(ptr=start;ptr;)
{
tmp=ptr->next;
ptr->next=prev;
prev=ptr;
ptr=tmp;
}
return prev;
}
Node*sort(Node*start,Node**p2last)
{
Node*ptr,*newNode,*tmp,*start1,*last1;
start1=last1=NULL;
while(start!=NULL)
{
tmp=ptr=start;
while(ptr)
{
if(tmp->data > ptr->data)
tmp=ptr;
ptr=ptr->next;
}
newNode=createNode(tmp->data);
start1=insertLast(start1,&last1,newNode);
start=Delete(start,p2last,tmp->data);
}
*p2last=last1;
return start1;
}
Node*sort2(Node*start,Node**p2last)
{
int *arr,count=0,i,tmp,j;
Node*ptr,*start1,*last1,*newNode;
ptr=start;
start1=last1=NULL;
while(ptr)
{
count++;
ptr=ptr->next;
}
arr=(int*)malloc(sizeof(int)*count);
ptr=start;
for(i=0;i<count;i++)
{
arr[i]=ptr->data;
ptr=ptr->next;
}
/* sorting the array bubble */
for(i=1;i<count;i++)
for(j=0;j<count-i;j++)
if(arr[j]>arr[j+1])
{
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
for(i=0;i<count;i++)
start1=insertLast(start1,&last1,createNode(arr[i]));
*p2last=last1;
return start1;
}

Related

Why am i getting segmentation fault in deleting node?

node * del(node * start,int loc)
{
int l=len(start);
if(loc<1 || loc>l)
{
printf("Deletion not possible. \n");
}
else
{
if(loc==1)
{
node *p;
p=start;
start=start->next;
free(p);
}
else
{
node *p,*q;
p=start;
for(int i=1;i<=loc-1;i++)//check this one.
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
printf("Deletion completed!\n");
}
return start;
}
This is the function and I am calling it from main() as:
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
While deleting any node I am getting segmentation fault!I am stuck at this .
Can anyone help?
here is the full program:-
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node * next;
};
typedef struct Node node;
int len(node * start)
{
if(start==NULL)
return 0;
int c=1;
while(start!=NULL)
{
start=start->next;
c++;
}
return c;
}
node * insert(node* start,int loc,int d)
{
int l=len(start);
node * p=start;
node * temp=(node*)malloc(sizeof(node));
if(loc<1 || loc>l+1)
{
printf("Insertion not posible.!\n");
return start;
}
if(l==0 || loc==1)
{
temp->next=start;
start=temp;
temp->data=d;
printf("Insertion completed.\n");
}
else
{
for(int i=1;i<=loc-2;i++)
p=p->next;
temp->next=p->next;
p->next=temp;
temp->data=d;
printf("Insertion completed. \n");
}
return start;
}
void show(node *start)
{
int l=len(start);
if(l==0)
{
printf("Nothing to print. \n");
}
else
{
for(int i=1;i<l-1;i++)
{
printf(" %d -> ",start->data);
start=start->next;
}
printf(" %d \n",start->data);
}
}
node * destroy(node * start)
{
node * p=start;
while(start!=NULL)
{
start=start->next;
free(p);
p=start;
}
printf("Destroy of linked list completed! .\n");
return NULL;
}
node * del(node * start,int loc)
{
int l=len(start);
if(loc<1 || loc>l)
{
printf("Deletion not possible. \n");
}
else
{
if(loc==1)
{
node *p;
p=start;
start=start->next;
free(p);
}
else
{
node *p,*q;
p=start;
for(int i=1;i<=loc-1;i++)//check this one.
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
printf("Deletion completed!\n");
}
return start;
}
int main()
{
node * start=NULL;
int ch,temp,d;
ch=temp=d=0;
while(ch != -1)
{
switch(ch)
{
case 0:
printf("Enter 0 to show menu.\n");
printf("Enter 1 to create linked list.\n");
printf("Enter 2 to destroy linked list.\n");
printf("Enter 3 to get the length of likned list.\n");
printf("Enter 4 to insert element in the linked list.\n");
printf("Enter 5 to delete element from the linked list.\n");
printf("Enter 6 to view the linked list.\n");
printf("Enter 7 to reverse a linked list.\n");
break;
case 1:
printf("Enter the size of link list to begin with.\n");
scanf("%d",&temp);
for(int i=1;i<=temp;i++)
{
printf("Enter the data to bes inserted to node %d .\n",i);
scanf("%d",&d);
start=insert(start,i,d);
}
break;
case 2:
start=destroy(start);
break;
case 3:
printf("Size of linked list is: %d \n",len(start));
break;
case 4:
printf("Enter the location where you want to insert the data.\n");
scanf("%d",&temp);
printf("Enter the data to be intered.\n");
scanf("%d",&d);
start=insert(start,temp,d);
break;
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
case 6:
show(start);
break;
default:
ch=0;
break;
}
printf("\nEnter your choice? \n");
scanf("%d",&ch);
}
destroy(start);
}
Change:
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
line scanf("%d",temp); to scanf("%d",&temp);

Double linked list - C

I'm trying to make a simple double linked list, I used (switch) in the first place:
int choice, data;
switch(choice)
{
case 1:
printf("Enter Your Data\n");
scanf("%d",&data);
InsetFirst(data);
data =0;
break;
case 2:
printf("Enter Your Data\n");
scanf("%d",&data);
InsertLast(data);
data =0;
break;
case 3:
printf("The list from the beginning to the End :\n");
PrintForward();
break;
case 4:
printf("The list from the end to the beginning\n");
PrintBackward();
break;
case 5:
printf("Enter the data you want search\n");
scanf("%d",data);
Search(data);
if(Search(data))
{
printf("%d\n",*(Search(data)));
}
else
{}
data =0;
break;
case 6:
printf("Enter The data you want to delete\n");
scanf("%d",&data);
DeleteNode(data);
break;
default :
printf("Not Valid Entry\n");
But it kept showing me this error in one of the functions
"expected declaration or statement at end of input"
knowing that I tested the functions individually and it worked properly,
After that I used (if,if-else) and then it worked`
int main()
{
int choice=1 , data;
while (1)
{
printf("Choose from the following options\n\n");
printf("1-Insert at the beginning\n2-Append\n3-Print Forward\n4-Print Backward\n5-Search\n6-Delete\n");
scanf("%d",&choice);
if(choice==1)
{
printf("Enter Your Data\n");
scanf("%d",&data);
InsetFirst(data);
data =0;
}
else if (choice==2)
{
printf("Enter Your Data\n");
scanf("%d",&data);
InsertLast(data);
data =0;
}
else if(choice==3)
{
printf("The list from the beginning to the End :\n");
PrintForward();
}
else if(choice==4)
{
printf("The list from the end to the beginning\n");
PrintBackward();
}
else if(choice==5)
{
printf("Enter the data you want search\n");
scanf("%d",data);
Search(data);
data =0;
}
else if(choice==6)
{
printf("Enter The data you want to delete\n");
scanf("%d",&data);
DeleteNode(data);
}
else
{
printf("Enter a Valid Choice\n");
}
}`,
but there were error with search function in case the item doesn't exist.
hope anyone can help me, thanks in advance, peace :)
here is the full code with commented sections that don't work:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node
{
int data;
struct Node* pnext;
struct Node* pprev;
};
struct Node* pstart = NULL;
struct Node* plast = NULL;
/** Functions Prototype **/
struct Node* CreatNode (void);
void InsetFirst (int data);
void InsertLast (int data);
void PrintForward (void);
void PrintBackward (void);
struct Node* Search (int data);
void DeleteNode (int Node );
int main()
{
int choice=1 , data;
while (1)
{
printf("Choose from the following options\n\n");
printf("1-Insert at the beginning\n2-Append\n3-Print Forward\n4-Print Backward\n5-Search\n6-Delete\n");
scanf("%d",&choice);
if(choice==1)
{
printf("Enter Your Data\n");
scanf("%d",&data);
InsetFirst(data);
data =0;
}
else if (choice==2)
{
printf("Enter Your Data\n");
scanf("%d",&data);
InsertLast(data);
data =0;
}
else if(choice==3)
{
printf("The list from the beginning to the End :\n");
PrintForward();
}
else if(choice==4)
{
printf("The list from the end to the beginning\n");
PrintBackward();
}
else if(choice==5)
{
printf("Enter the data you want search\n");
scanf("%d",data);
Search(data);
data =0;
}
else if(choice==6)
{
printf("Enter The data you want to delete\n");
scanf("%d",&data);
DeleteNode(data);
}
else
{
printf("Enter a Valid Choice\n");
}
}
/*
int choice,data;
switch(choice)
{
case 1:
printf("Enter Your Data\n");
scanf("%d",&data);
InsetFirst(data);
data =0;
break;
case 2:
printf("Enter Your Data\n");
scanf("%d",&data);
InsertLast(data);
data =0;
break;
case 3:
printf("The list from the beginning to the End :\n");
PrintForward();
break;
case 4:
printf("The list from the end to the beginning\n");
PrintBackward();
break;
case 5:
printf("Enter the data you want search\n");
scanf("%d",data);
Search(data);
if(Search(data))
{
printf("%d\n",*(Search(data)));
}
else
{}
data =0;
break;
case 6:
printf("Enter The data you want to delete\n");
scanf("%d",&data);
DeleteNode(data);
break;
default :
printf("Not Valid Entry\n");
*/
return 0;
}
/** Function to create Node in the list **/
struct Node* CreatNode (void)
{
struct Node* temp;
temp = (struct Node*) malloc(sizeof(struct Node));
if (!temp)
{
printf("\nNot Enough Memory");
}
else
{
return temp;
}
}
/**************************************************************************************/
/** Function to Insert Node at the Beginning of the list **/
void InsetFirst (int data)
{
struct Node* temp;
temp = CreatNode();
temp ->data = data;
temp ->pnext = NULL;
temp ->pprev = NULL;
if (pstart == NULL)
{
pstart = temp;
plast = temp;
}
else
{
temp ->pnext = pstart;
pstart ->pprev =temp;
pstart = temp;
}
}
/***********************************************************************************/
/** Function to Insert Node at the End of the List **/
void InsertLast (int data)
{
struct Node* temp;
temp = CreatNode();
temp ->data = data;
temp ->pnext = NULL;
temp ->pprev = NULL;
if (pstart == NULL)
{
pstart = temp;
plast = temp;
}
else
{
temp ->pprev = plast;
plast ->pnext = temp;
plast = temp;
}
}
/**********************************************************************************************/
/** Function to Print the list From the beginning to the End **/
void PrintForward (void)
{
struct Node* current;
current = pstart;
printf("\nThe list From the Beginning to the End :\n");
while (current)
{
printf("\n%d",current->data);
current = current->pnext;
}
printf("\n");
}
/*********************************************************************************************/
void PrintBackward (void)
{
struct Node* current;
current = plast;
printf("\nThe list From End to the Beginning :\n");
while (current)
{
printf("\n%d",current->data);
current = current->pprev;
}
printf("\n");
}
/*********************************************************************************************/
/** Function To Find a Given Data **/
struct Node* Search (int data)
{
struct Node* current;
current = pstart;
if (current)
{
while(current)
{
if (current->data == data)
{
return current;
}
current = current->pnext;
}
printf("\nIt's not found\n");
return NULL;
}
}
/**************************************************************************************/
/** Function to Delete a Given Node **/
void DeleteNode (int Node )
{
struct Node* state;
state = Search(Node);
if (state)
{
if ((state == pstart) && (state == plast))
{
pstart = NULL;
plast = NULL;
}
else if (pstart == state)
{
pstart = state->pnext;
state->pnext->pprev = NULL;
}
else if (plast == state)
{
plast = state->pprev;
state->pprev->pnext = NULL;
}
else
{
state->pprev->pnext = state->pnext;
state->pnext->pprev = state->pprev;
}
free(state);
}
else
{
printf("NOT Found\n");
}
}
There was a few problems in your code. I was working with the switch version, and there were also problems with the if else version.
case 5:
printf("Enter the data you want search\n");
scanf("%d",data);
Search(data);
if(Search(data))
{
printf("%d\n",*(Search(data)));
}
else
{}
data =0;
break;
When you use scanf you need to send a pointer to the location where you want to store something, so it will be scanf("%d", &data). Also printf's %d needs int value as argument but here:
printf("%d\n",*(Search(data)));
you are sending it a Node, and so it will not accept it. You need to send the data that is within the Node so you do this:
printf("%d\n",(*(Search(data))).data);
And you don't need to have else with an empty block, if you remove it it won't affect the program.
Now we have a problem in the CreatNode function which does not return anything in the case temp is null. So you need to return null in the if block in case there was not enough memory:
struct Node* CreatNode (void)
{
struct Node* temp;
temp = (struct Node*) malloc(sizeof(struct Node));
if (!temp)
{
printf("\nNot Enough Memory");
return NULL; //YOU NEED TO RETURN NULL HERE
}
else
{
return temp;
}
}
Function Search won't return anything if for example first current equals NULL, so you need to move return and printf line out of if block like this:
struct Node* Search (int data)
{
struct Node* current;
current = pstart;
if (current)
{
while(current)
{
if (current->data == data)
{
return current;
}
current = current->pnext;
}
}
printf("\nIt's not found\n");
return NULL;
}
And the last thing and the reason why your switch does not work is because it is not in a loop. Switch by itself is not a loop so you need to put it in a while loop that works until for example, user enters 0. So this will be a solution:
int main()
{
int choice=-1,data;
while(choice != 0)
{
printf("\n\nChoose from the following options\n\n");
printf("1-Insert at the beginning\n2-Append\n3-Print Forward\n4-Print Backward\n5-Search\n6-Delete\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
/*...*/
case 2:
/*...*/
case 3:
/*...*/
case 4:
/*...*/
case 5:
/*...*/
case 6:
/*...*/
case 0:
break;
default :
printf("Not Valid Entry\n");
}
}
return 0;
}

linked list insertion operation and display

I am trying to implement a singly linked list and performing insertion operations.The program compiles and runs but whenever i try to display its elements.It doesn't show the elements.I am not able to find out the error.
#include <stdio.h>
#include <stdlib.h>
struct n
{
int data;
struct n *next;
};
typedef struct n node;
node *insert_at_front(node *start,int info)
{
node *temp,*p;
temp=(node *)malloc(sizeof(node));
temp->data=info;
temp->next=start;
start=temp;
return start;
}
node *insert_at_end(node *start,int info)
{
node *temp,*p;
temp=(node *)malloc(sizeof(node));
if(start==NULL)
{
printf("Empty\n");
return start;
}
else
{
for(p=start; p->next!=NULL; p=p->next)
{
if(p->next==NULL)
{
temp->data=info;
temp->next=p->next;
p->next=temp;
}
}
}
return start;
}
node *insert_after(node *start,int info,int dat)
{
node *temp,*p;
temp=(node *)malloc(sizeof(node));
for(p=start; p->next!=NULL; p=p->next)
{
if(p->data==dat)
{
temp->data=info;
temp->next=p->next;
p->next=temp;
}
}
return start;
}
void display(node *start)
{
node *temp;
if(start==NULL)
{
printf("List is Empty\n");
return ;
}
temp=start;
while(temp!=NULL)
{
printf("%d-->",temp->data);
temp=temp->next;
}
printf("\n\n");
}
int main()
{
int value;
node *start=NULL;
int choice,data1;
while(1)
{
printf("\n1.insert_at_start\n2.insert at end.\n3.insert_after");
printf("\n4.display\n");
printf("enter choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter value\n");
scanf("%d",&value);
insert_at_front(start,value);
break;
case 2:
printf("Enter value\n");
scanf("%d",&value);
insert_at_end(start,value);
break;
case 3:
printf("Enter value\n");
printf("Enter value after which you want to insert\n");
scanf("%d%d",&value,&data1);
insert_after(start,value,data1);
break;
case 4:
display(start);
break;
default:
break;
}
}
return 0;
}
One problem with your code is that you're not using the return values from the different insert procedures. This means that if you start with an empty list (NULL) there is no way that main can get a non-empty list back.
At least you need to update start, for example:
start = insert_at_front(start,value);

AddNew Function using Linked List In C

Question: Create a linked list containing values in the ascending values. Then write functions addNew() which will accept a value from the user and then call addBegin() and addafterValue() functions to add the input value in the appropriate place
e.g. consider the list is like this:
12,15,20,26 then if the user enters values 8, 16 & 30 the list will look like this: 8,12,15,16,20,26,30.
My program:
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE *start=NULL;
void append()
{
NODE *temp,*ptr;
temp=(NODE *)malloc(sizeof(NODE));
printf("Enter data:");
scanf("%d",&temp->data);
temp->next=NULL;
if(start==NULL)
start=temp;
else
{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=temp;
}
}
void display()
{
NODE *ptr=start;
while(ptr!=NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void addBegin(int val)
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
temp->data=val;
temp->next=start;
start=temp;
}
unsigned int addAfterValue(int val,NODE *ptr)
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
temp->data=val;
temp->next=ptr->next;
return temp;
}
void addNew()
{
int val;
unsigned int loc;
NODE *ptr=start;
printf("Enter value to add:");
scanf("%d",&val);
if(val<ptr->data) {
addBegin(val);
ptr=NULL;
}
while(ptr!=NULL) {
if(ptr->next!=NULL)
{
if(val<ptr->next->data)
{
addAfterValue(val,ptr);
ptr->next=loc;
ptr=NULL;
}
else
{
ptr=ptr->next;
}
}
if(ptr->next==NULL)
{
loc=addAfterValue(val,ptr);
ptr=NULL;
}
}
}
int main()
{
int ans;
do
{
printf("Enter [1]To append\n[2]To add new node\n[3]To display\n[0]To exit\n");
printf("Enter your choice:");
scanf("%d",&ans);
switch(ans)
{
case 1:
append();
break;
case 2:
addNew();
break;
case 3:
display();
break;
case 0:
break;
default:
printf("Wrong Input.Try again.");
}
}while(ans);
}
My doubt: The addBegin() function works perfectly. I think there's something wrong with addafterValue(). Can anyone help me by finding out my mistake?
Instead of passing the current pointer address.
Use the previous node pointer and assign to its next node.
void addAfterValue(int val,NODE *ptr)
{
NODE *temp = (NODE *)malloc(sizeof(NODE));
temp->data=val;
temp->next=ptr->next;
ptr->next = temp;
}
Change the addNew function
void addNew()
{
int val;
NODE *ptr=start;
NODE *prev= NULL;
printf("Enter value to add:");
scanf("%d",&val);
if( ptr == NULL || val < ptr->data)
{
addBegin(val);
return;
}
else
{
prev = ptr;
ptr=ptr->next;
}
while( ptr != NULL)
{
if( val <= ptr->data)
{
addAfterValue(val,prev);
return;
}
else
{
prev = ptr;
ptr=ptr->next;
}
}
/* Control comes here if the entire list is scanned.... Now append it to the end using prev pointer, as the new node is greater than all of the existing nodes */
}

How to insert node at begin ,end and selected position in singly linked list?

I am new for c programming ,i have tried myself inserting node in singly linked list program but i didn't get a proper output and i dont have any idea to correct my program if anybody knows please help.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
int loc;
void addbegin(int num)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if(head=NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
void addend(int num)
{
struct node *temp1,*temp2;
temp1=(struct node *)malloc(sizeof(struct node));
temp1->data=num;
temp2=head;
if(head==NULL)
{
head=temp1;
head->next=NULL;
}
else
{
while(temp2->next != NULL)
temp2=temp2->next;
temp1->next=NULL;
temp2->next=temp1;
}
}
void pos(int num,int loc)
{
int length();
struct node *temp,*cur_ptr,*prev_ptr;
int i;
cur_ptr=head;
if(loc > (length()+1) || loc<= 0)
{
printf("it is illegal call:");
}
else
{
if(loc == 1)
{
addbegin(num);
}
else
{
for(i=1;i<loc;i++)
{
prev_ptr=cur_ptr;
cur_ptr=cur_ptr->next;
}
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
prev_ptr->next=temp;
temp->next=cur_ptr;
}
}
}
int length()
{
struct node *cur_ptr;
int count = 0;
cur_ptr=head;
while(cur_ptr!=NULL)
{
cur_ptr=cur_ptr->next;
count++;
}
return(count);
}
void display()
{
struct node *temp=NULL;
if(temp==NULL)
{
printf("list is empty:");
}
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
int main()
{
int num;
head=NULL;
int choice;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert at begin\n");
printf("2.insert at end\n");
printf("3.insert at selected position\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&choice)<=0)
{
printf("Enter only an Integer\n");
}
printf("enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the number to insert at begin : ");
scanf("%d",&num);
addbegin(num);
break;
case 2: printf("Enter the number to insert at end: ");
scanf("%d",&num);
addend(num);
break;
case 3: printf("Enter the number to insert at selected position: ");
scanf("%d",&num);
pos(num,loc);
break;
case 4: printf("display the values");
display();
break;
case 5: printf("exit");
display();
}
}
return 0;
}
i think the error is in my main function but am not clear in that please help
In your addbeginmethod there's at least one obvious error:
if(head=NULL)
should be
if (head == NULL)
as you need to compare, not assign.
In your posmethod you have a function declaration: int length(); which shouldn't be there, but rather at the top, before main.
Another issue, this time in the display method:
void display()
{
struct node *temp=NULL;
if(temp==NULL) {
printf("List is empty:");
}
while(temp!=NULL) {
printf("%d",temp->data);
temp=temp->next;
}
}
Here temp will always be NULL, I guess you meant to assign headto the temppointer, otherwise it will never traverse the list.
And finally, in the insert at specific position choice you need to ask for a location value and pass that along too the function call, so add a declaration for int loc;in main, and change the third case to this:
case 3:
printf("Enter the number to insert at selected position: ");
scanf("%d",&num);
printf("Enter the position: ");
scanf("%d",&loc);
pos(num,loc);
break;
to the
Finally I'm going to quote from the C99 standard, section 5.1.2.2.1 Program startup:
The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as
argc and argv, though any names may be used, as they are local to the
function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
So, please, change your declaration of mainand include a returnline at the end (possibly return 0;indicating successful program exit).
This became rather lengthy. After the suggested changes your program should look something like this:
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
}*head;
void addbegin(int num)
{
struct node *temp;
temp = malloc(sizeof(struct node));
temp->data=num;
if(head==NULL) {
head=temp;
head->next=NULL;
} else {
temp->next=head;
head=temp;
}
}
void addend(int num)
{
struct node *temp1, *temp2;
temp1 = malloc(sizeof(struct node));
temp1->data = num;
temp2 = head;
if(head == NULL) {
head = temp1;
head->next = NULL;
} else {
while(temp2->next != NULL)
temp2=temp2->next;
temp1->next=NULL;
temp2->next=temp1;
}
}
int length()
{
struct node *cur_ptr;
int count = 0;
cur_ptr = head;
while(cur_ptr != NULL) {
cur_ptr = cur_ptr->next;
count++;
}
return (count);
}
void pos(int num, int loc)
{
struct node *temp, *cur_ptr, *prev_ptr;
int i;
cur_ptr=head;
if(loc > (length()+1) || loc<= 0) {
printf("it is illegal call:");
} else {
if(loc == 1) {
addbegin(num);
} else {
for(i=1; i<loc; i++) {
prev_ptr=cur_ptr;
cur_ptr=cur_ptr->next;
}
temp = malloc(sizeof(struct node));
temp->data=num;
prev_ptr->next=temp;
temp->next=cur_ptr;
}
}
}
void display()
{
struct node *temp = head;
if(temp == NULL) {
printf("List is empty:");
}
printf("The list contains the following values:\n");
while(temp!=NULL) {
printf("%d\n",temp->data);
temp=temp->next;
}
}
int main()
{
int choice, num, loc;
head = NULL;
while(1) {
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert at begin\n");
printf("2.insert at end\n");
printf("3.Insert at selected position\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&choice)<=0) {
printf("Enter only an Integer\n");
}
switch(choice) {
case 1:
printf("Enter the number to insert at begin : ");
scanf("%d",&num);
addbegin(num);
break;
case 2:
printf("Enter the number to insert at end: ");
scanf("%d",&num);
addend(num);
break;
case 3:
printf("Enter the number to insert at selected position: ");
scanf("%d",&num);
printf("Enter the position: ");
scanf("%d",&loc);
pos(num,loc);
break;
case 4:
printf("Display the values\n");
display();
break;
case 5:
printf("exit");
exit(0); // maybe you should exit here.
display();
}
}
return 0;
}
void addbegin(int num)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if(head==NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
and
void display()
{
struct node *temp=NULL;
temp = head;
if(temp==NULL)
{
printf("list is empty:");
}
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
int loc;
void addbegin(int num)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if(head==NULL) //this not assign, you need == to compare
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
void addend(int num)
{
struct node *temp1,*temp2;
temp1=(struct node *)malloc(sizeof(struct node));
temp1->data=num;
temp2=head;
if(head==NULL)
{
head=temp1;
head->next=NULL;
}
else
{
while(temp2->next != NULL)
temp2=temp2->next;
temp1->next=NULL;
temp2->next=temp1;
}
}
int length()
{
struct node *cur_ptr;
int count = 0;
cur_ptr=head;
while(cur_ptr!=NULL)
{
cur_ptr=cur_ptr->next;
count++;
}
return(count);
}
void pos(int num,int loc)
{
struct node *temp,*cur_ptr,*prev_ptr;
int i;
cur_ptr=head;
if(loc > (length()+1) || loc<= 0)
{
printf("it is illegal call:");
}
else
{
if(loc == 1)
{
addbegin(num);
}
else
{
for(i=1;i<loc;i++)
{
prev_ptr=cur_ptr;
cur_ptr=cur_ptr->next;
}
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
prev_ptr->next=temp;
temp->next=cur_ptr;
}
}
}
void display()
{
struct node *temp=head;
if(temp==NULL)
{
printf("list is empty:");
}
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
int num;
int choice;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert at begin\n");
printf("2.insert at end\n");
printf("3.insert at selected position\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&choice)<=0)
{
printf("Enter only an Integer\n");
}
switch(choice)
{
case 1: printf("Enter the number to insert at begin : ");
scanf("%d",&num);
addbegin(num);
break;
case 2: printf("Enter the number to insert at end: ");
scanf("%d",&num);
addend(num);
break;
case 3: printf("Enter the number to insert at selected position: ");
scanf("%d",&num);
pos(num,loc);
break;
case 4: printf("\ndisplay the values: ");
display();
break;
case 5: printf("exit");
display();
}
}
return 0;
}
Try this
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
int loc;
void addbegin(int num)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if(head==NULL) //this not assign, you need == to compare
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
void addend(int num)
{
struct node *temp1,*temp2;
temp1=(struct node *)malloc(sizeof(struct node));
temp1->data=num;
temp2=head;
if(head==NULL)
{
head=temp1;
head->next=NULL;
}
else
{
while(temp2->next != NULL)
temp2=temp2->next;
temp1->next=NULL;
temp2->next=temp1;
}
}
int length()
{
struct node *cur_ptr;
int count = 0;
cur_ptr=head;
while(cur_ptr!=NULL)
{
cur_ptr=cur_ptr->next;
count++;
}
return(count);
}
void pos(int num,int loc)
{
struct node *temp,*cur_ptr,*prev_ptr;
int i;
cur_ptr=head;
if(loc > (length()+1) || loc<= 0)
{
printf("it is illegal call:");
}
else
{
if(loc == 1)
{
addbegin(num);
}
else
{
for(i=1;i<loc;i++)
{
prev_ptr=cur_ptr;
cur_ptr=cur_ptr->next;
}
temp=(struct node*)malloc(sizeof(struct node));
temp->data=num;
prev_ptr->next=temp;
temp->next=cur_ptr;
}
}
}
void display()
{
struct node *temp=head;
if(temp==NULL)
{
printf("list is empty:");
}
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
int num;
int choice;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert at begin\n");
printf("2.insert at end\n");
printf("3.insert at selected position\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&choice)<=0)
{
printf("Enter only an Integer\n");
}
switch(choice)
{
case 1: printf("Enter the number to insert at begin : ");
scanf("%d",&num);
addbegin(num);
break;
case 2: printf("Enter the number to insert at end: ");
scanf("%d",&num);
addend(num);
break;
case 3: printf("Enter the number to insert at selected position: ");
scanf("%d",&num);
printf("Enter the position to insert: 1 for insert at begin, so on: ");
scanf("%d",&loc);
pos(num,loc);
break;
case 4: printf("\ndisplay the values: ");
display();
break;
case 5:
display();
printf("\n exiting program \n");
exit(0);
}
}
return 0;
}
Try this:
#include<iostream>
using namespace std;
struct stu{
int id;
stu *next = NULL;
};
stu *first = NULL;
stu *last = NULL;
int opt;
void insert_end();
void display();
int main(){
do{
cout<<"\n\n0.Exit";
cout<<"\n1.Insert at end in linked list";
cout<<"\n2.Display linked list";
cout<<"\n\nEnter your choice: ";
cin>>opt;
switch(opt){
case 1:{
insert_end_list1();
break;
}
case 2:{
display_list1();
break;
}
}
}
while(opt != 0);
return 0;
}
void insert_end(){
stu *current = new stu;
cout<<"\n\nEnter the student id:";
cin>>current->id;
if(first == NULL){
cout<<"\n\nEmpty linked list";
first = last = current;
}
else{
last->next = current;
last = current;
}
}
void display(){
stu *p = first;
while(p != NULL){
cout<<p->id<<" ";
p = p->next;
}
}
This code uses structure for creation of a new node in singly linked list.

Resources