Why am i getting segmentation fault in deleting node? - c

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);

Related

Implementing linked list in C

I am trying to implement linked list in C, having options for creation, insertion, deletion and display.
My code is:
#include <stdio.h>
#include <conio.h>
void createFirst(int);
void appendNode(int);
void insertFirst(int);
void insertNode(int,int);
void deleteFirst();
void deleteNode(int);
void display();
struct Node
{
int data;
struct Node *link;
};
typedef struct Node Node;
Node *start = NULL;
int count=0;
void main()
{
int ch;
do
{
printf("\f\n");
printf("1. Create the list \n");
printf("2. Insert an element at any position \n");
printf("3. Delete an element at any position \n");
printf("4. Display the list \n");
printf("5. Quit \n");
printf("Enter your choice : \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int a;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
createFirst(a);
while(1)
{
printf("Do you want to continue[Y/N] : \n");
scanf(" %c",&c);
if(c=='Y' || c=='y')
{
printf("Enter the data : \n");
scanf("%d",&a);
appendNode(a);
}
else if(c=='N' || c=='n')
{
break;
}
else
{
continue;
}
}
break;
}
case 2:
{
int a,pos;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
}
break;
}
case 3:
{
int pos;
char c;
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
}
break;
}
case 4:
{
display();
break;
}
case 5:
{
return;
}
default:
{
printf("Invalid choice \n");
break;
}
}
}while(ch!=5);
}
void createFirst(int d)
{
Node newnode = {d,NULL};
start = &newnode;
count++;
}
void appendNode(int d)
{
Node temp = *start;
while(temp.link != NULL)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
temp.link = &newnode;
count++;
}
void insertFirst(int d)
{
Node newnode = {d,NULL};
newnode.link = start;
start = &newnode;
count++;
}
void insertNode(int n,int d)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
newnode.link = temp.link;
temp.link = &newnode;
}
void deleteFirst()
{
if(start != NULL)
{
printf("Deleted element : %d \n",(*start).data);
start = (*start).link;
count--;
}
else
{
printf("Underflow \n");
}
}
void deleteNode(int n)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
printf("Deleted node : %d",temp.link->data);
temp = *(temp.link->link);
count--;
}
void display()
{
if(start == NULL)
{
printf("The list is empty \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<=count;i++)
{
printf("%d ",temp.data);
temp = *temp.link;
}
}
But:
Whenever the control is going to appendNode function, the program terminates somehow.
After only creating the first node, if i go to display, it is printing some garbage value.
Please somebody help.
Your problem is on the line (inside of appendNode) which contains this: Node temp = *start;. Don't do it that way. Do it this way:
Node *temp = start;
Change the following pointer notations to accomodate this change. Like change the dot operators to the -> operator. Here's the rest of the function:
while(temp->link != NULL)
{
temp = temp->link;
}
Node *newnode = malloc (sizeof(struct Node));
newnode->data = 0;
newnode->link = NULL;
temp->link = newnode;
count++;

Unexpected behaiviour, when trying to enter a new element in a linked List

So, I have to read a linked list from a binary file and then add new elements to it. It reads from the binary as expected, but when I try to add new elements to the list, it adds only the last one, which I enter.
Here is the code in main() responsible for reading, creating and inserting a new element into the List
int main()
{
int choice=0;
int confirmation=0;
t_Node *temp_node1, *temp_node2, *temphead;
unsigned int ID1, ID2;
FILE *fp;
fp = fopen("Data.bin","rb");
if(fp==NULL)
{
printf("File error");
exit(6);
}
while(1)
{
if(feof(fp))
{
break;
}
if (head == NULL)
{
head = readNode(fp);
temphead = head;
}else
{
temphead = readlist(temphead, fp);
}
}
fclose(fp);
while(1)
{
printf("\n\n");
printf("Hello world!\n\n 1-Enter a new element/s.\n 2-Copy data from one element to another (by ID).\n 3-Switch data between two elements (by ID).\n 4-Delete an element (by ID)\n 5-Print all elements\n 6-Delete all elements\n 0-Exit\n");
scanf("%d",&choice);
if(choice==0)
{
system("cls");
delete_List(head);
printf("EXIT BY USER");
break;
}
switch(choice)
{
case 1:
system("cls");
int temp=0;
t_Node *temphead1, *searched1, *searched2;
do
{
temphead1=makelist(temphead);
printf("press 0 to stop, any other key to go on\n");
fflush(stdin);
scanf("%d",&temp);
}while (temp!=0);
break;
case 2:
system("cls");
confirmation=0;
ID1=0;
ID2=0;
do
{
do
{
printf("Enter ID of the element you want to copy\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
}while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
do{
do{
printf("Enter ID of the element you want to copy to\n");
scanf("%u",&ID2);
temp_node2=Find_By_Id(ID2);
}while(temp_node2==NULL);
printNode(temp_node2);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
Copy_first_to_second(temp_node1, temp_node2);
break;
case 3:
system("cls");
ID1=0;
ID2=0;
do{
do{
printf("Enter ID of the first element you want to switch data with\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
}while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for Yes, 0 for No\n");
scanf("%d",&confirmation);
} while (confirmation==0);
confirmation=0;
do
{
do
{
printf("Enter ID of the second element you want to switch data with\n");
scanf("%u",&ID2);
temp_node2=Find_By_Id(ID2);
} while( temp_node2==NULL);
printNode(temp_node2);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while(confirmation==0);
confirmation=0;
Copy_first_to_second(temp_node1, temp_node2);
break;
case 4:
system("cls");
ID1=0;
do
{
do
{
printf("Enter ID of the element you want to delete\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
} while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
Delete_Element(temp_node1);
break;
case 5:
system("cls");
if (head==NULL)
{
printf("\nEnter elements first");
break;
}
printlist(head);
break;
case 6:
system("cls");
delete_List(head);
printf("List deleted");
break;
default:
delete_List(head);
exit(1);
}
}
return 0;
}
The structures:
typedef struct something
{
char name[50];
double value;
unsigned int ID;
}t_Something;
typedef struct node
{
t_Something smth;
struct node *next;
}t_Node;
And the functions:
t_Something readElement (FILE *file)
{
t_Something t_Struct;
int check=0;
unsigned int t_ID;
fread(&t_Struct,sizeof(t_Struct),1,file);
do{
t_ID=t_Struct.ID;
check=checkID(t_ID);
if (check==1)
{
break;
}
}while(1);
return t_Struct;
}
t_Something addElement()
{
t_Something t_Struct;
int check=0;
unsigned int t_ID;
printf("\nInput name\t");
fflush(stdin);
gets(t_Struct.name);
printf("\nInput value\t");
fflush(stdin);
scanf("%0.2lf",&t_Struct.value);
printf("\nInput ID, must be unique\t");
fflush(stdin);
do
{
scanf("%u",&t_Struct.ID);
t_ID=t_Struct.ID;
check=checkID(t_ID);
if (check==1)
{
break;
}
}while (1);
return t_Struct;
}
t_Node* addNode (t_Node *temphead)
{
t_Node *pNode;
pNode = (t_Node*)malloc(sizeof(t_Node));
if (pNode==NULL)
{
printf("\nMemory error\n");
delete_List(head);
}
pNode->smth=addElement();
pNode->next=NULL;
return pNode;
}
t_Node* makelist(t_Node *temphead)
{
t_Node *temp2=addNode(temphead);
temphead->next=temp2;
return temp2;
}
t_Node* readNode (FILE *file)
{
t_Node *pNode;
pNode = (t_Node*)malloc(sizeof(t_Node));
if (pNode==NULL)
{
printf("\nMemory error\n");
delete_List(head);
}
pNode->smth=readElement(file);
pNode->next=NULL;
return pNode;
}
t_Node* readlist (t_Node *temphead, FILE *file)
{
t_Node *temp2=readNode(file);
temphead->next=temp2;
return temphead->next;
}
void printlist (t_Node* current){
for (;;){
printNode(current);
current=current->next;
if (current==NULL) break;
}
}
void printNode (t_Node* current)
{
printf("\n--------\n");
printf("name: %s\n", current->smth.name);
printf("value: %lf", current->smth.value);
printf("\nID: %u\n", current->smth.ID);
}
void delete_List (t_Node* current)
{
t_Node *temp;
for (;;){
temp=current->next;
free(current);
current=temp;
if (current==NULL)
{
break;
}
}
}
int checkID (unsigned int number)
{
t_Node *current=head;
int pass=1;
if (head!=NULL)
{
for(;;)
{
if(current->smth.ID==number)
{
pass=0;
return pass;
}
current=current->next;
if (current==NULL)
{
break;
}
}
}
return pass;
}
t_Node* Find_By_Id (unsigned int searched)
{
t_Node* current=head;
for (;;)
{
if (searched==current->smth.ID)
{
return current;
}
current=current->next;
if (current==NULL)
{
break;
}
}
printf("\nThere is no element with this ID\n");
return NULL;
}
void Change_two_elements (t_Node* first, t_Node* second)
{
t_Something temp;
temp=first->smth;
first->smth=second->smth;
second->smth=temp;
}
void Copy_first_to_second (t_Node* first, t_Node* second)
{
second->smth=first->smth;
}
void Delete_Element (t_Node* element)
{
t_Node* temp;
if (element==head)
{
head=element->next;
free(element);
}else
{
for(temp=head;;)
{
if (temp->next==element)
{
break;
}
temp=temp->next;
}
temp->next=element->next;
free(element);
}
}
Sorry for the large amount of code, but otherwise it wouldn't be possible to see the full picture

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);

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.

Linked list implementation in 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;
}

Resources