C语言仿照有头结点单链表的存储和基本操作,设计双向链表-非循环链表(初始化、插入、输出)。
时间: 2023-05-28 22:06:13 浏览: 128
```
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点结构体
typedef struct Node {
int data;
struct Node *prev;
struct Node *next;
} Node;
// 初始化双向链表,返回头结点指针
Node *init() {
Node *head = (Node *)malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
return head;
}
// 在双向链表的第pos个位置插入值为val的节点
int insert(Node *head, int pos, int val) {
int i = 0;
Node *p = head;
// 寻找第pos个节点的前一个节点p
while (p->next && i < pos-1) {
p = p->next;
i++;
}
// pos值不合法
if (!p || i > pos-1) {
printf("插入失败,pos值不合法!\n");
return -1;
}
// 创建新节点并插入p和p->next之间
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
newNode->prev = p;
newNode->next = p->next;
p->next->prev = newNode;
p->next = newNode;
return 0;
}
// 输出双向链表
void printList(Node *head) {
Node *p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = init(); // 初始化双向链表
int pos, val;
// 从标准输入读入插入操作,输入格式为:pos val,其中pos为插入位置,val为插入值
while (scanf("%d%d", &pos, &val) != EOF) {
insert(head, pos, val); // 插入节点
printList(head); // 输出双向链表
}
return 0;
}
```
使用示例:
输入:
```
1 1
1 2
2 3
3 4
5 5
```
输出:
```
1
2 1
2 3 1
2 3 4 1
插入失败,pos值不合法!
2 3 4 1
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)