Hello,
I got working code of Linked List here. But I having a problem with adding an item.
I added four numbers in the Linked List. First, I added 2 then 8 then 4 and the last one 16. The result would be like this:
[IMG]http://i168.photobucket.com/albums/u162/SHENGTON/display-1.jpg[/IMG]
What I want to happen is, whatever the first item that I added in the list would be the first list in the list and so on.
So if I added "2,8,4,16" the result should be:
The linked list contains: 2
The linked list contains: 8
The linked list contains: 4
The linked list contains: 16
NOT like this:
The linked list contains: 16
The linked list contains: 4
The linked list contains: 8
The linked list contains: 2
Here's my code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct listel
{
int val;
struct listel *next;
struct listel *curr;
struct listel *head;
struct listel *temp;
struct listel *q;
struct listel *m;
struct listel *search;
}item;
void display(item *curr,item *head);
struct listel *search(item *head);
void delete(item *curr,item *head,int x);
int main()
{
int i,cho,x,pop=0;
item *head,*curr;
head=NULL;
clrscr();
do
{
printf("\n\n [1] Add item\n");
printf(" [2] Display items\n");
printf(" [3] Search an item\n");
printf(" [4] Delete an item\n");
printf(" [5] Exit\n\n");
printf(" Enter your choice:");
scanf("%3d",&cho);
i = getchar();
if(cho==1)
{
clrscr();
printf("\n Enter the element you want to add: ");
scanf("%3d",&x);
curr=(item*)malloc(sizeof(item));
curr->val = x;
curr->next = head;
head=curr;
pop=1;
}
else if(cho==2 && pop)
{
display(curr,head);
}
else if(cho==3 && pop)
{
search(head);
}
else if(cho==4 && pop)
{
delete(head,curr,x);
}
else
{
clrscr();
printf(" _____________________\n | \t\t |");
printf("\n | The list is empty. |\n");
printf(" |_____________________|");
}
}
while(cho != 5);
{
clrscr();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t ___________________\n\n\t\t\t Press Enter to Exit");
printf("\n\t\t\t ___________________");
i = getchar();
++i;
}
clrscr();
return 0;
}
void display(item *curr,item *head)
{
curr=head;
clrscr();
while(curr != NULL)
{
printf("\n The linked list contains:%3d",curr->val);
curr=curr->next;
}
}
struct listel *search(item *head)
{
int x,found=0;
item *temp;
temp=head;
clrscr();
printf("\n Enter the data that you want to search: ");
scanf("%d",&x);
while(temp)
{
if(temp->val==x)
{
found=1;
}
temp=temp->next;
}
if(found == 1)
{
printf("\n %d is found in the list.",x);
}
else
{
printf("\n %d is not found in the list.",x);
}
return(temp);
}
void delete(item *curr,item *head,int x)
{
item *temp,*m;
temp=curr;
clrscr();
printf("\n Enter the element to delete: ");
scanf("%d",&x);
while(temp)
{
if(temp->val == x)
{
printf("\n %d has been deleted.",x);
if (temp==head)
{
head=temp->next;
free(temp);
return;
}
else
{
m->next=temp->next;
free(temp);
return;
}
}
else
{
m=temp;
temp=temp->next;
}
}
printf("\n No such entry to delete.");
}