#include <stdio.h> #include <stdlib.h> #include "LinkList.h" Node *InitList() { Node *first; first=(Node *)malloc(sizeof(Node)); first->next=NULL; return first; } void PrintList(Node *first) { Node *p; p=first->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("\n"); } /*使用尾插法建立单链表,并返回指向单链表的头结点的指针*/ Node *CreateAtTail(DataType a[],int n) { int i; Node *first,*s,*r; first=InitList(); //初始化单链表 r=first; for(i=0;i<n;i++) { s=(Node *)malloc(sizeof(Node)); s->data=a[i]; r->next=s; r=s; } r->next=NULL; return first; } void Insert(Node *first,int i,DataType x) { Node *p=first,*s; int count=0; /**********Begin***************/ /**********End*****************/ } 请补全以上代码并且平台会对你编写的代码进行测试: 主函数代码如下: int main() { Node *first; int a[5],i,pos,x; for(i=0;i<5;i++) { scanf("%d",&a[i]); } first=CreateAtTail(a,5); scanf("%d",&pos); //插入位置 scanf("%d",&x); //插入值 Insert(first,pos,x); PrintList(first); } 运行示例,在第4个位置插入6: 1 2 3 4 5 4 6 1 2 3 6 4 5 运行示例: 1 2 3 4 5 7 8 插入位置错误
时间: 2025-05-09 20:17:39 浏览: 29
### 单链表插入节点的实现
以下是基于已有引用内容以及专业知识完成的单链表插入节点的操作代码。此代码实现了在指定位置插入一个新节点的功能。
#### 定义结构体
首先定义单链表的节点结构体,这已在引用中给出:
```c
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
```
#### 初始化函数
初始化单链表时创建头节点并将其 `next` 设置为空[^1]:
```c
LinkList InitList() {
LinkList L = (LinkList)malloc(sizeof(LNode));
if (!L) {
printf("内存分配失败\n");
exit(-1);
}
L->next = NULL; // 初始指向空链表
return L;
}
```
#### 插入节点功能
下面是一个完整的插入节点函数,支持在任意位置插入新的节点。如果插入的位置超出范围,则默认将该节点追加到链表末尾。
```c
bool InsertNode(LinkList L, int pos, int value) {
if (pos < 0) { // 如果位置小于零则返回错误
printf("插入位置不合法\n");
return false;
}
LNode *p = L; // p 指向头节点
int i = 0;
// 找到第 pos-1 个节点
while (p && i < pos - 1) {
p = p->next;
++i;
}
if (!p || i > pos - 1) { // 超过链表长度,默认追加到最后
p = GetLastNode(L); // 获取最后一个节点
if (!p) { // 链表为空的情况
p = L;
}
}
// 创建新节点
LNode *newNode = (LNode *)malloc(sizeof(LNode));
newNode->data = value;
newNode->next = p->next; // 新节点指向原下一个节点
p->next = newNode; // 当前节点指向新节点
return true;
}
// 辅助函数:获取链表中的最后一个节点
LNode* GetLastNode(LinkList L) {
LNode *p = L;
while (p->next != NULL) {
p = p->next;
}
return p;
}
```
上述代码逻辑清晰地处理了多种情况:
- **非法输入**:当给定的插入位置为负数时会提示错误。
- **越界处理**:如果插入位置超出了当前链表的最大索引,则自动将节点附加至链表末端。
- **正常插入**:找到目标位置后,在其之前插入新节点,并调整指针关系[^4]。
#### 测试代码
为了验证以上代码的有效性,可以编写简单的测试程序来演示插入过程。
```c
void PrintList(LinkList L) {
LNode *p = L->next; // 不打印头节点的数据部分
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkList L = InitList(); // 初始化链表
// 向链表中依次插入几个节点用于测试
InsertNode(L, 0, 10);
InsertNode(L, 1, 20);
InsertNode(L, 2, 30);
printf("插入后的链表: ");
PrintList(L);
// 尝试在中间位置插入一个新的节点
InsertNode(L, 1, 15);
printf("在第二个位置插入15后的链表: ");
PrintList(L);
// 尝试在不存在的位置插入节点(应被追加)
InsertNode(L, 10, 99);
printf("尝试在超过边界处插入99后的链表: ");
PrintList(L);
free(L); // 清理资源
return 0;
}
```
运行结果可能类似于以下形式:
```
插入后的链表: 10 20 30
在第二个位置插入15后的链表: 10 15 20 30
尝试在超过边界处插入99后的链表: 10 15 20 30 99
```
---
###
阅读全文
相关推荐



















