这是我在单循环链表中的第 n 个位置插入节点的代码。当 tail 是NULL时,我试图返回,但这给了我一个运行时错误。对于这个特定的代码,我打印了 8 而 tail 是NULL而不是什么时候pos == 1应该是这样。对于这种错误的插入模式,我会在display()调用时以相反的顺序打印一个列表。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
struct node *tail;
void insert(int data, int pos) {
struct node *temp1 = (struct node *)malloc(sizeof(struct node));
temp1->data = data;
struct node *temp2;
if (tail == NULL) {
temp1->link = temp1;
tail = temp1;
}
if (pos == 1) {
temp1->link = tail->link;
tail->link = temp1;
} else {
temp2 = tail->link;
for (int i = 1; i < pos - 1; i++) {
temp2 = temp2->link;
}
temp1->link = temp2->link;
temp2->link = temp1;
}
}
void display() {
printf("List is \n");
if (tail == NULL) {
return;
}
struct node *temp;
temp = tail->link;
do {
printf("%d ", temp->data);
temp = temp->link;
} while (temp != tail->link);
printf("\n");
}
main() {
tail = NULL;
insert(8, 1);
display();
insert(3, 2);
display();
insert(7, 3);
display();
insert(9, 4);
display();
}
它打印9->7->3->8而不是8->3->7->9。