-
LinkedList Problem
I trying to make a doubly linklist. I am not getting what is wrong with below code.
Code:
#define TRUE 1
#define FALSE 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode{
int id;
char name[70];
struct ListNode *prev,*next;
};
int AddNodetoList(struct ListNode * first,struct ListNode * lst){
if(lst == NULL){
printf("\nGive Some Data\n");
}else{
if(first == NULL){
first = lst;
}else{
if(first->next == NULL){
first->next = lst;
lst->next = first;
first->prev = lst;
lst->prev = first;
}else{
lst->prev = first->prev;
lst->prev->next = lst;
first->prev = lst;
lst->next = first;
}
}
}
return TRUE;
}
int DisplayAll(struct ListNode * first){
struct ListNode * temp;
if(first == NULL){
printf("\nThere is no Data");
}else{
if(first->next == NULL){
printf("\n----|%s|-------",first->name);
}else{
temp = first->next;
printf("\n----|%s|-------",first->name);
printf("\n----|%s|-------",first->next->name);
while(first != temp->next){
printf("\n----|%s|-------",temp->next->name);
temp = temp->next;
}
}
}
return TRUE;
}
int main(){
struct ListNode * temp;
struct ListNode * first;
first = NULL;
long choice,i;
do{
printf("\nEnter a Selection");
printf("\n1. Add Node");
printf("\n2. Delete Node");
printf("\n3. Display All ");
printf("\n4. Delete All node");
printf("\n5. Exit\n\n\n");
scanf("%d",&choice);
switch(choice){
case 1:
for(i=0;i<100;i++){
temp = malloc(sizeof(struct ListNode));
if(temp == NULL){
printf("\nOut of Memory");
printf("\n%d\n",i);
exit(0);
}else{
strcpy(temp->name,"Hello Shiju Samuel");
AddNodetoList(first,temp);
}
}
break;
case 2:
break;
case 3:
DisplayAll(first);
break;
case 4:
break;
}
}while (choice != 5);
return EXIT_SUCCESS;
}
-
For starters, your Add function always returns true.
Next, to change what a pointer outside the function points to, inside a function, you need to pass a pointer to a pointer. That way the change actually takes effect.
Code:
void foo( struct Node **list, struct node *bar; )
{
*list = bar; /* make the list point to bar now */
}
...
struct Node *list, *bar;
...
foo( &list, bar );
On an aside, don't just say "What's wrong?" Tell us what it is:
a) Supposed to do.
b) Doing.
c) Not doing.
Quzah.
-
Tell me, how is your list in main getting added to if you don't return the modified list from AddNodetoList, nor pass a pointer to a pointer to the list when you give it to AddNodetoList? Once you do one of those it will be easier to verify whether your algorithm to add to the list works or not.