链表显示相反

时间:2015-05-20 09:55:34

标签: c list

我正在尝试单个链表。创建列表后,它会尝试以正向顺序显示,但它会反向显示。我想我正在向前位置添加节点,但为什么它会从最后一个输入值显示?

这是代码

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
void add(num);
void insert();
void display();
struct node
{
int val;
struct node *next;
};

struct node *head =NULL;

main()
{

int data,i=0;
head = (struct node *)malloc(sizeof(struct node));
while(1)
    {
      printf("enter your choice");
      scanf("%d",&i);

      switch(i)
       {
         case 1:
         insert();
         break;

         case 2:
         display();
         break;

         default:
         printf("thankyou");

        }

      }



}

void add(num)
{
  struct node *temp;
  temp=(struct node *)malloc(sizeof(struct node));
  temp->val=num;
  if (head== NULL)
      {
       head=temp;
       head->next=NULL;
      }
  else
      {
       head->next = temp
       head=temp;
      }
}

void insert()
{
  int ch;
  if (head->val == NULL )
     {
       printf("Enter the value for the first node :");
       scanf("%d",&ch);
       add(ch);
      }
  else if(head->val != NULL)
      {
       printf("Enter the value to insert :");
       scanf("%d",&ch);
       add(ch);
      }
  }

void display()
{
 struct node *newnode;
 newnode = head;
  if(newnode == NULL)
       printf("invalid list");
  else
     {
       while(newnode!=NULL)
        {
          printf("%d \t\t",newnode->val);
          newnode=newnode->next;

         }
     } 
 }

3 个答案:

答案 0 :(得分:1)

而不是做

    head->next = temp;
    head=temp;

    temp->next=head;
    head=temp;

答案 1 :(得分:0)

您可以在列表末尾附加每个新实体:

void add(num)
{
  struct node *temp, *temp2;
  temp=(struct node *)malloc(sizeof(struct node));
  temp->val=num;
  if (head== NULL)
      {
       head=temp;
       head->next=NULL;
      }
  else
      {
       temp2 = head;
       while (temp2->next != NULL)
            temp2 = temp2->next;

       temp2->next = temp;
       temp->next = NULL;
      }
}

答案 2 :(得分:0)

代码对我来说看起来不太好,因为在所有插入结束时,头部指向列表的最后一个元素,next字段未初始化。这不会反向打印列表,这将打印插入的最后一个元素,然后行为将是未定义的。此外,当你松开头指针时,你已经丢失了列表和所有分配的内存(泄漏)。

我建议保留一个tail指针,它总是指向列表的尾部。追加函数只需在tail之后添加新节点,并通过推进它来更新tailhead保持不变,并指向列表的第一个元素。您还可以将head的值分配给临时变量,迭代到列表的末尾,然后插入,但在这种情况下,插入将是昂贵的。

相关问题