C编程-通过迭代方法反转链接



我正在尝试反转一个通过迭代链接的方法。神奇的是,在观看了教程并尝试重新编码后,该程序成功运行。然而,当我回顾代码时,我遇到了一个问题:在第23行,为什么我们必须使用temp1->下一个而不是temp1?当遍历到链表的末尾时,在哪种情况下我们使用条件(节点!=NULL(?在哪种情况下我们使用(节点的链接!=NULL(?如果有人能启发我,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* Insert(struct Node* head, int data)
{
struct Node* temp = (struct Node*) malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
//If the list is empty
if (head == NULL)
{
head = temp;
}
else //The list is not empty
{
struct Node* temp1 = head;
while (temp1->next != NULL)
{
temp1 = temp1->next;
}
temp1->next = temp;
}
return head;
}
void Print(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("n");
}
struct Node* Reverse(struct Node* head)
{
struct Node* *prev, *current, *next;
current = head;
prev = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
int main()
{
struct Node* head = NULL;

printf("Enter the length of the linked list you want to create: ");
int length;
scanf("%d", &length);
printf("Enter the value you want to input: ");
int i;
for (i = 0; i < length; i++)
{
int x;
scanf("%d", &x);
head = Insert(head, x);
}

printf("Given linked listn"); 
Print(head); 
head = Reverse(head);  
printf("nReversed linked list n"); 
Print(head); 
return 0;
}

在这种情况下,在while条件中的第23行,您可以注意到程序正在使用temp1 = temp1->next,如果在到达链表的最后一个元素时将条件更改为temp1 != NULL,它将从内存中收集垃圾,甚至导致错误,因为NULL没有下一个位置。

因此,如果要访问列表中的数据,请使用temp1 != NULL;如果要操作链表的下一个位置,则使用temp1->next != NULL

因为链表末尾的temp1->nextNULL,但最后一个节点有数据,如果使用temp1 == NULL,则会说最后一个结点是NULL,但事实并非如此。因此,当";指向下一个节点的指针";是NULL,而不是当下一个节点是NULL时。

最新更新