#include <stdio.h>
#include <stdlib.h>
struct Node
{
int val;
struct Node *next;
};
struct List
{
struct Node *head;
struct Node *tail;
};
typedef struct List *List;
void Print(List temp)
{
struct Node* print = temp->head;
while(print->next!=NULL)
{
printf("%d ", print->next->val);
print->next = print->next->next;
}
printf("nn");
}
int main()
{
int i;
List Numbers;
Numbers = (struct List *) malloc(sizeof(struct List));
if (Numbers== NULL)
printf("Out of memory!n");
Numbers->head = (struct Node *) malloc(sizeof(struct Node));
if (Numbers->head == NULL)
printf("Out of memory!n");
Numbers->head->next = NULL;
Numbers->tail = Numbers->head;
printf("Enter 5 numbers:");
struct Node* temp = Numbers->head;
for(i=0;i<5;i++)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
scanf("%d", &newnode->val);
newnode->next = NULL;
temp->next = newnode;
temp = newnode;
Numbers->tail = newnode;
}
Print(Numbers);
Print(Numbers);
return 0;
}
当我第一次打印列表时,它打印正确,但第二次它什么都不打印,程序崩溃。我不知道为什么列表会被销毁,尽管我正在使用临时节点打印它。我应该更改打印功能吗?还是问题出在其他地方?
您的问题来自以下行:
print->next = print->next->next;
这一行改变了head->next
的指针。当您第一次运行它时,head->next
的指针将更改为每个节点,并在末尾设置为NULL
。要修复它,只需将其更改为:
print = print->next;
然后,您可以在不更改原始链表的情况下正确打印链表。
您可能想要将print->next = print->next->next;
更改为print = print->next;
。