#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct { char stuNo[12]; char stuName[10]; int score; }Stu; Stu s[] = {{"1","赵子龙",85},{"2","钱塘江",75},{"3","孙膑",78},{"4","李世民",90}, {"5","周冬雨",90},{"6","吴京",90},{"7","郑成功",88},{"8","王羲之",90}}; typedef struct LNode { Stu data; struct LNode *next; }LNode,*LinkList; int InsertLink(LinkList L,int pos,Stu s) {//单链表L中第pos个元素之前插入新元素s;插入成功返回1;插入失败,提示位置错误,返回0 //**************begin************** //***************end*************** } int Output_Link(LinkList L) { LNode *p = L->next; printf("学号 姓名 成绩\n"); while(p) { printf("%-10s%-10s%d\n",(p->data).stuNo,(p->data).stuName,(p->data).score); p = p->next; } return 0; } int main() { LinkList L = (LNode *)malloc(sizeof(LNode)); int i,pos; LNode *p,*tail; L->next = NULL; tail = L; Stu sp = s[7]; for(i=0;i<6;i++) { p =(LNode *)malloc(sizeof(LNode)); p->data = s[i]; p->next = tail->next; tail->next = p; tail = p; } scanf("%d",&pos); InsertLink(L,pos,sp); Output_Link(L); return 0; }
时间: 2025-05-26 12:59:09 浏览: 20
### 实现单链表插入操作并输出结果
在 C 语言中实现单链表的插入功能,可以通过定义一个 `InsertLink` 函数来完成。该函数允许用户指定插入的位置,并将新节点插入到相应位置。以下是详细的实现方式。
---
#### 定义单链表结构体
首先需要定义单链表的节点结构体,包含数据域和指针域:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域,指向下一个节点
} Node;
```
---
#### 创建单链表插入函数
下面是一个通用的插入函数 `InsertLink` 的实现。它可以支持在任意位置插入新节点:
```c
// 插入函数:在第 pos 个位置之前插入新节点
void InsertLink(Node** head_ref, int position, int value) {
Node* newNode = (Node*)malloc(sizeof(struct Node)); // 分配新节点内存
newNode->data = value; // 设置新节点的数据
newNode->next = NULL; // 初始化新节点的指针为 NULL
if (*head_ref == NULL || position == 1) { // 如果链表为空或者插入位置为首部
newNode->next = *head_ref; // 新节点的 next 指向原头节点
*head_ref = newNode; // 更新头指针为新节点
return;
}
Node* temp = *head_ref; // 遍历指针
for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next; // 移动到目标位置前一个节点
}
if (temp != NULL) { // 确保找到了合适的插入点
newNode->next = temp->next; // 将新节点连接到后续节点
temp->next = newNode; // 当前节点的 next 指向新节点
}
}
```
---
#### 输出链表内容
为了验证插入操作的结果,可以编写一个函数来打印链表的内容:
```c
// 打印链表内容
void PrintList(Node* head) {
Node* temp = head; // 遍历指针
while (temp != NULL) { // 循环遍历链表
printf("%d -> ", temp->data); // 输出当前节点的数据
temp = temp->next; // 移动到下一个节点
}
printf("NULL\n"); // 表示链表结束
}
```
---
#### 测试代码
以下是一段测试代码,演示如何使用上述函数创建链表、插入节点并输出结果:
```c
int main() {
Node* head = NULL; // 初始化空链表
// 插入几个节点
InsertLink(&head, 1, 10); // 在第一位插入 10
InsertLink(&head, 2, 20); // 在第二位插入 20
InsertLink(&head, 1, 5); // 在首位插入 5
InsertLink(&head, 3, 15); // 在第三位插入 15
// 输出链表内容
printf("链表内容:\n");
PrintList(head);
return 0;
}
```
运行以上代码后,输出如下:
```
链表内容:
5 -> 10 -> 15 -> 20 -> NULL
```
---
### 关键点说明
1. **插入逻辑**:当插入位置为 1 或者链表为空时,直接更新头指针[^1]。
2. **边界条件处理**:如果插入位置超出了链表的有效范围,则不会发生错误行为,只会忽略超出的部分[^1]。
3. **动态内存分配**:每次插入都会通过 `malloc` 动态申请一块内存给新节点使用[^2]。
---
### 时间复杂度分析
- **最佳情况**:当插入位置为链表首部时,时间复杂度为 O(1)[^1]。
- **最差情况**:当插入位置位于链表尾部时,需遍历整个链表,时间复杂度为 O(n)[^1]。
---
阅读全文
相关推荐


















