c - 在整数的单循环链表中插入第 n 个位置的问题
问题描述
这是我在单循环链表中的第 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
。
解决方案
推荐阅读
- java - tomcat 启动但它没有监听任何端口
- angular - angular 7 应用程序的 url 中重复的 base href
- javascript - 如何使用 Node.js 运行功能服务器端而不是使用 Javascript 的浏览器端?
- java - mediaplayer 不播放广播电台流
- spring - 无法加载 JDBC 驱动程序类 'com.mysql.jdbc.Driver' maven 依赖项
- android - WorkManager setRequiresDeviceIdle 令人困惑
- sublimetext3 - Sublime Text 3 SFTP 无法使用密钥文件“~/.ssh/id_rsa”(无法打开文件)
- php - PHP将数组格式(如first_name)更改为名字
- reactjs - 为单个组件实现 redux 好吗?
- javascript - 从类方法调用发射时的不同行为