繁体   English   中英

在链表的末尾插入节点

[英]Inserting a node at the end of 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;
}

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

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;
}

据我所知,在评论的部分

// for traversing to the end

实施迭代太过分了; 条件应该是

while ( temp1->next != NULL )

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM