我写了一个程序,以降序的顺序将节点插入到链表中,但是每当我用编号12,14,13,19,7
的顺序测试代码时,每当我输入7时,列表中就已经有7个了,但是很容易看出7不是出现此错误后,如果输入2来选择打印选项,则程序进入无限循环。看不到错误,我感到很困惑。
#include <stdio.h>
#include <stdlib.h>
struct node {
int content;
struct node* nextLink;
};
typedef struct node NODE;
void print (NODE*);
int insertNode (NODE** head, int x);
int main (void)
{
int num, choice;
NODE* head;
head = NULL;
do {
printf("\nPlease press 1 to insert or press 2 to print or press 0 to exit\n");
scanf("%d", &choice);
switch (choice) {
case 0:
return 0;
break;
case 1:
printf("Enter an integer to insert into the linkedlist: ");
printf("\n");
scanf("%d", &num);
insertNode(&head, num);
break;
case 2:
print(head);
break;
default:
printf("You entered an invalid number\n");
return 0;
break;
}
} while (choice == 1 || choice == 2);
return 0;
}
int insertNode (NODE** head, int i)
{
NODE* newNode;
newNode = (NODE*)malloc(sizeof(NODE));
newNode->content = i;
NODE* temporary = *head;
newNode->nextLink = NULL;
if ((*head == NULL) || ((*head)->content) < i) {
*head = newNode;
(*head)->nextLink = temporary;
}
else {
do {
if (((temporary->content) > i) && ((temporary->nextLink->content) < i)) {
newNode->nextLink = temporary->nextLink;
temporary->nextLink = newNode;
return;
}
else if (temporary->content == i) {
printf("To be inserted value is already in the list\n");
return;
}
temporary = temporary->nextLink;
} while (temporary->nextLink != NULL);
if (temporary->content == i) {
printf("To be inserted value is already in the list\n");
return;
}
temporary->nextLink = newNode;
}
return 0;
}
void print (NODE* head)
{
if (head == NULL) {
printf("\nLinkedList is empty \n");
}
while (head != NULL) {
printf("%d ", head->content);
head = head->nextLink;
}
}
最佳答案
我编译并运行它,除了一件事,它似乎运行良好。 insertNode
被定义为返回一个int,但是return语句中有3个是void返回。为了进行编译,我将它们更改为return 0;
。如果您能够按原样编译并运行它,则可能是由于不一致的返回值破坏了堆栈。
关于c - 插入链表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5438161/