【发布时间】:2021-07-12 15:41:24
【问题描述】:
我正在尝试制作一个循环链表。当我在创建列表后尝试显示列表时,程序不断崩溃。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node * next;
} node;
node * createList(int);
void display(node * head);
int main() {
struct node * head;
head = createList(5);
display(head);
}
node * createList(int n) {
int i = 0,data = 0;
struct node * head = NULL;
struct node * temp = NULL;
struct node * p = NULL;
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
temp->next = head;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
void display(node * head) {
struct node * temp = head->next;
while (temp != head) {
printf("%d-> \t",temp->data);
temp = temp->next;
}
printf("\n");
}
我做错了什么?
【问题讨论】:
-
提示:解释这行代码:
temp->next = head;它的目标是什么? (它会导致while (p->next != NULL) {永远循环。) -
循环列表中不会有
while (p->next != NULL)--- 最后一个节点->next 指针指向头节点(因此是循环列表)
标签: c data-structures linked-list circular-list