Linked list program only printing last two nodes of list

271 views Asked by At

I wrote a program to create and print a single linked list. I have used structure pointer to structure pointer for modifying the list. When I print the list it only prints last two nodes added.

#include<stdio.h>
#include<stdlib.h>

struct node{
        int data;
        struct node *next;
};

struct node * createnode(int num){
        struct node * n;
        n=(struct node*)malloc(sizeof(struct node));
        n->data=num;
        n->next=NULL;
        return n;
}
                                                  
void createlist(struct node **head,int num){
        struct node *temp=createnode(num);
        *head=temp;
        return;
}                                                 
void options(){
        printf("Enter your choice\n");
        printf("1.Add at end\n");
        printf("2.Add at beginning\n");
        printf("3.Add at location\n");
        printf("4.Print list\n");                 
}

void add_end(struct node **head){
        int info;
        printf("Value: ");
        scanf("%d",&info);
        if(*head==NULL){
                createlist(head,info);
                return;
        }
        struct node *temp=createnode(info);
        struct node **end=head;
        while((*end)->next!=NULL){
                (*end)=(*end)->next;
        }
        (*end)->next=temp;                        
}                 

void print2(struct node *head){
        struct node * temp=head;
        printf("\nList :");
        while(temp!=NULL){
                printf("%d ",temp->data);
                temp=temp->next;
        }
        printf("\n");
}

int main(){
        struct node *head=NULL;
        createlist(&head,5);

        int choice=0;
        options();
        scanf("%d",&choice);
        while(1){
                switch(choice){
                case 1:add_end(&head);
                       break;
                case 4:print2(head);
                       break;
                default:exit(0);
                }
                options();
                scanf("%d",&choice);
        }

        return 0;
}

Each time, I append 5 to 6 nodes at the end of list and when I print the list, it only prints last to nodes added. I don't know it is wrong with add_end function or print function.

1

There are 1 answers

2
Viktor Latypov On BEST ANSWER

Your add_line routine incorrectly searches for the last node. The end variable is a pointer to pointer, so it is in a sense equivalent to the head parameter and it is not a temporary value, as it should be. Change the last lines to something like this:

void add_end(struct node **head){
    ...
    struct node *end = *head;
    while (end->next) {
           end = end->next;
           // Original line overwrites the 'head':  (*end)=(*end)->next;
    }
    end->next=temp;                        
}