在链表的末尾插入节点

时间:2014-12-10 15:17:54

标签: c data-structures singly-linked-list

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

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

int main() {
  struct node* head = NULL;
  struct node* second = NULL;
  struct node* third = NULL;

  head = (struct node*)malloc(sizeof(struct node));
  second = (struct node*)malloc(sizeof(struct node));
  third = (struct node*)malloc(sizeof(struct node));

  head->data = 1;
  head->next = second;

  second->data = 2;
  second->next = third;

  third->data = 3;
  third->next = NULL;

  struct node* temp;
  temp = head;

  while (temp != NULL) { // for printing the linked list
    printf("%d ",temp->data);
    temp = temp->next;
  }

  struct node* new1;
  struct node* temp1;

  temp1 = head;

  while (temp1 != NULL) { // for traversing to the end
    temp1 = temp1->next;
  }

  new1 = (struct node*)malloc(sizeof(struct node));

  new1->data = 5;
  new1->next = NULL;

  temp1->next = new1;

  while (temp1 != NULL) { // again for printing the list
    printf("%d ",temp1->data);
    temp1 = temp1->next;
  }

  return 0;
}

我正在尝试在链接列表的末尾插入一个节点,但它无法正常工作。我成功创建了链表,但我无法在最后插入节点。 这就是我老师教给我的东西,但它没有用。

2 个答案:

答案 0 :(得分:2)

while(temp1 != NULL)          // for traversing to the end
{
    temp1 = temp1->next;
}

这将循环直到temp1 NULL。您需要改为获取最后一个节点,即当temp1->nextNULL时,例如

while(temp1->next != NULL)          // for traversing to the end
{
    temp1 = temp1->next;
}

答案 1 :(得分:2)

据我所知,在评论的部分

// for traversing to the end

实施迭代太多;条件应该是

while ( temp1->next != NULL )

在到达最后一个节点时立即终止,而不是在到达终止NULL指针时终止。