Вставка в связанный список на c

#c #linked-list

#c #связанный список

Вопрос:

Я хочу просмотреть связанный список и распечатать все элементы связанного списка до конца.
я делаю следующее

 #include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int main()
{
    struct linkedList   //making user defined linked list
    {
        int num;
        struct linkedList *ptr;
    };
    int choice=1,last=0;
    typedef struct linkedList node;   
    node *temp,*lasst,*head;      //initialization of pointers.
    while(choice==1)
    {
        temp=(node *)malloc(sizeof(node)); //allocation of memory to temp
        printf("enter num");
        scanf("%d",amp;temp->num);
        if(last==0)
        {
            lasst=head=temp;
        }
        else
        {
            lasst->ptr=temp;
            lasst=temp;
        }
        printf("do u want to enter more data? type 1");
        scanf("%d",amp;choice);
    }
    lasst->ptr=0;
    temp=head;
    while(temp!=0)
    {
        printf("%d =>",temp->num);
        temp=temp->ptr;
    }

}
  

Я хочу напечатать все элементы, присутствующие в связанном списке, но мой код печатает только последний элемент связанного списка, что мне делать?

Комментарии:

1. «Что мне делать?» — Возьмите отладчик и пройдитесь по коду, чтобы выяснить, что происходит. Отладка является неотъемлемой частью обучения программированию.

2. Вы никогда не меняете last , тем самым всегда вставляя в начало (и утечку памяти). Мое предложение — переименовать (глупо) lasst в last и рассматривать значение last == NULL как условие для вставки в начало.

Ответ №1:

Это полный код вставки узла в связанный список. Он может вставлять начало узла, конец, после и до узла.

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

    struct node
    {
        int info;
        struct node *link;
    }*new1,*first=NULL,*save,*pred;

    struct node *insert_begin(int x,struct node *first);
    struct node *insert_end(int x,struct node *first);
    struct node *insert_after(int x,struct node *first);
    struct node *insert_before(int x,struct node *first);
    void display(struct node *first);

    void main()
    {
        int x,ch,c=0;
        //clrscr();
        do
        {
        printf("n_____________________________________________n");
        printf("n1 - Insert Node At the Begining of the Node");
        printf("n2 - Insert Node At the Ending of the Node");
        printf("n3 - Insert Node At the After Particular Node");
        printf("n4 - Insert Node At the Before Particular Node");
        printf("n_____________________________________________n");

        printf("ntEnter Your Choice Here -->");
        scanf("%d",amp;ch);

        printf("nEnter Value To Insert In The Node -->");
        scanf("%d",amp;x);

        switch(ch)
        {
            case 1:
                first=insert_begin(x,first);
                break;
            case 2:
                first=insert_end(x,first);
                break;
            case 3:
                first=insert_after(x,first);
                break;
            case 4:
                first=insert_before(x,first);
                break;
            default:
                printf("nPlease Reenter Choice....");
                break;
        }

        display(first);

        printf("nDo You Want To Continue.. Press 1 For Continue -->");
        scanf("%d",amp;c);
        }while(c==1);
        //getch();
    }

    void display(struct node *first)
    {
        printf("n**********************************************n");
        printf("n-----NODES ARE BELOW-----n");

        while(first!=NULL)
        {
            printf(" [ %d ]  ",first->info);
            first=first->link;
        }
        printf("n**********************************************n");
    }

    struct node *insert_begin(int x,struct node *first)
    {
        new1=(struct node*)malloc(sizeof(struct node));
        new1->info=x;
        new1->link=NULL;

        if(first==NULL)
        {
            first=new1;
        }
        else
        {
            new1->link=first;
            first=new1;
        }
        return first;
    }

    struct node *insert_end(int x,struct node *first)
    {
        new1=(struct node*)malloc(sizeof(struct node));
        new1->info=x;
        new1->link=NULL;
        save=first;

        if(first==NULL)
        {
            first=new1;
              //    save=first;
        }
        else
        {
            while(save->link!=NULL)
            {
                save=save->link;
            }
            save->link=new1;
        }
       //   save=first;
        return first;
    }
    struct node *insert_after(int x,struct node *first)
    {
        int v;
        new1=(struct node*)malloc(sizeof(struct node));
        new1->info=x;
        new1->link=NULL;
        save=first;

        printf("nEnter Node Value Which Insert After Above Node =");
        scanf("%d",amp;v);

        if(first==NULL)
        {
            first=new1;
            save=first;
        }
        else
        {
            if(first->link==NULL)
            {
                new1->link=first;
                first=new1;
            }
            else
            {
                while(save->link!=NULL amp;amp; save->info!=v)
                {
                    save=save->link;
                }
                new1->link=save->link;
                save->link=new1;
             }
        }
        save=first;
        return first;
    }
    struct node *insert_before(int x,struct node *first)
    {
        int v;
        new1=(struct node*)malloc(sizeof(struct node));
        new1->info=x;
        new1->link=NULL;
        save=first;

        printf("nEnter Value of node Which Insert Before Above Node =");
        scanf("%d",amp;v);

        if(first==NULL)
        {
            first=new1;
        }
        else
        {
            if(first->link==NULL)
            {
                new1->link=first;
                first=new1;
            }
            else
            {
                while(save->link!=NULL amp;amp; save->info!=v)
                {
                    pred=save;
                    save=save->link;
                }
                pred->link=new1;
                new1->link=save;
            }
        }
        return first;
    }