C 在单循环整数链表的第n个位置插入问题
下面是我在单循环链表的第n个位置插入节点的代码。当tail为C 在单循环整数链表的第n个位置插入问题,c,data-structures,linked-list,C,Data Structures,Linked List,下面是我在单循环链表的第n个位置插入节点的代码。当tail为NULL时,我试图返回,但这会导致运行时错误。对于这个特定的代码,当tail为NULL时打印8,而当pos==1时打印8,应该是这样。对于这个错误的插入模式,当调用display()时,我得到一个以相反顺序打印的列表 #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *link; }; stru
NULL
时,我试图返回,但这会导致运行时错误。对于这个特定的代码,当tail为NULL
时打印8,而当pos==1时打印8,应该是这样。对于这个错误的插入模式,当调用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();
}
#包括
#包括
结构节点{
int数据;
结构节点*链接;
};
结构节点*尾部;
无效插入(整数数据,整数位置){
结构节点*temp1=(结构节点*)malloc(sizeof(结构节点));
temp1->data=数据;
结构节点*temp2;
if(tail==NULL){
temp1->link=temp1;
tail=temp1;
}
如果(位置==1){
temp1->link=tail->link;
尾部->链接=temp1;
}否则{
temp2=尾部->链接;
对于(int i=1;ilink;
}
temp1->link=temp2->link;
temp2->link=temp1;
}
}
无效显示(){
printf(“列表是\n”);
if(tail==NULL){
返回;
}
结构节点*temp;
温度=尾部->链接;
做{
printf(“%d”,临时->数据);
温度=温度->链接;
}同时(温度!=尾部->链接);
printf(“\n”);
}
main(){
tail=NULL;
插入(8,1);
显示();
插入(3,2);
显示();
插入(7,3);
显示();
插入(9,4);
显示();
}
它打印的是9->7->3->8
,而不是8->3->7->9
,请编辑您的问题,并将整个代码正确缩进后发布。我们需要查看您的struct节点
定义和显示
函数。你的代码应该编译干净,可以下载,并且可以由响应者运行。按照你的代码结构,当添加到空列表时,在设置tail
后,你仍然会尝试定期插入代码。return
aftertail=temp1
或使用else if(pos==1)…
我已经编辑并给出了整个代码。您的insert
函数完全错误。您似乎希望tail
指向列表中的最后一个元素,但当您在(新的)最后一个位置插入新元素时,不会重置tail
。tail==NULL是我认为错误的地方。只需在if体中添加一个return语句,就不会得到任何输出。分配tail=temp1会为第一次插入调用提供一个垃圾值。应该是什么?请编辑您的问题并发布完整的代码,正确缩进。我们需要查看您的struct节点
定义和显示
函数。你的代码应该编译干净,可以下载,并且可以由响应者运行。按照你的代码结构,当添加到空列表时,在设置tail
后,你仍然会尝试定期插入代码。return
aftertail=temp1
或使用else if(pos==1)…
我已经编辑并给出了整个代码。您的insert
函数完全错误。您似乎希望tail
指向列表中的最后一个元素,但当您在(新的)最后一个位置插入新元素时,不会重置tail
。tail==NULL是我认为错误的地方。只需在if体中添加一个return语句,就不会得到任何输出。分配tail=temp1会为第一次插入调用提供一个垃圾值。这个角落应该是什么?