下面我编写了一个程序来检测并使用C从列表中删除循环。我收到运行时错误,但我找不到它?
#include <stdio.h>
#include <stdlib.h>
//node definition
struct node {
int key;
struct node *next;
};
// This function will make a new node
struct node *newNode(int key) {
struct node *temp = (struct node*)(malloc)(sizeof(struct node));
temp->key = key;
temp->next = NULL;
}
//This function will detect and remove a loop from linked list
void detect(struct node *head) {
struct node *slow = head;
struct node *fast = head->next;
while (fast && fast->next) {
if (slow == fast)
break;
slow = slow->next;
fast = fast->next->next;
}
if (slow == fast) {
slow = head;
while (slow != fast->next) {
slow = slow->next;
fast = fast->next;
}
fast->next = NULL;
}
}
//This function will print list
void print(struct node *head) {
struct node *temp = head;
while (temp != NULL) {
printf("%d ", temp->key);
temp = temp->next;
}
}
//This function is driver method
int main() {
struct node *head = newNode(10);
head->next = newNode(20);
head->next->next = newNode(30);
head->next->next->next = newNode(40);
head->next->next->next->next = newNode(50);
head->next->next->next->next->next = head->next->next;
detect(head);
print(head);
return 0;
}
答案 0 :(得分:2)
函数newNode不返回任何内容,这与原型不一致
查看代码,您应该在函数末尾添加return temp
。