我编写了一个程序,按照降序将节点插入到链表中。但每当我按照这个顺序用数字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;
}
}
答案 0 :(得分:0)
我编译并运行它,除了一件事似乎工作正常。 insertNode
被定义为返回一个int,但返回语句中有3个是void返回。为了使其编译,我将它们更改为return 0;
。如果你能够按原样编译和运行它,那么可能是堆栈被不一致的返回所破坏。
答案 1 :(得分:0)
如果要插入的前两个值按降序排列,则代码将无法运行。这会给分段错误。
要插入第二个元素,您需要小心
所以在之后条件
else if (temporary->content > i && temporary->nextLink==NULL)
(*head)->nextLink = newNode;
答案 2 :(得分:0)
你的代码做得太多了。如果您对它进行不同的编码,则没有特殊情况(例如在顶部插入,在列表的尾部插入)。
int insertNode (NODE **head, int val)
{
NODE *newnode;
for ( ; *head; head = &(*head)->nextLink) {
if ( (*head)->content == val) {
printf("To be inserted value (%d)is already in the list\n", val);
return 0;
}
if ( (*head)->content > val) break;
}
newnode = malloc(sizeof *newnode); // Maybe check return here ;-)
newnode->content = val;
newnode->nextLink = *head;
*head = newnode;
return 1;
}