解题思路:
该程序根据输入的操作类型进行相应的操作:
- 当操作为0时,程序会打印双向链表中的所有元素。
- 当操作为1时,程序会在指定位置插入一个整数。
- 当操作为2时,程序会从指定位置删除一个整数。
使用双向链表来存储整数,每个节点包含整数值、指向前一个节点的指针和指向下一个节点的指针。
注意事项:
在 createNode函数中,需要为新节点分配内存,并将整数值赋给节点的成员变量。
在 insertNode函数中,需要根据指定的位置插入新节点,注意处理头节点和中间节点的情况。
在 deleteNode函数中,需要根据指定的位置删除节点,注意处理头节点和中间节点的情况。
在 printList函数中,需要遍历链表并打印每个节点的整数值。
参考代码:
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点结构体
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 函数声明
Node* createNode(int data);
Node* insertNode(Node* head, int position, int data);
Node* deleteNode(Node* head, int position);
void printList(Node* head);
int main() {
Node* head = NULL;
int operation, position, data;
while (scanf("%d", &operation) != EOF) {
if (operation == 0) {
// 输出双向链表中的所有元素
printList(head);
} else if (operation == 1) {
// 插入一个整数到双向链表中
scanf("%d %d", &position, &data);
head = insertNode(head, position, data);
} else if (operation == 2) {
// 从双向链表中删除一个整数
scanf("%d", &position);
head = deleteNode(head, position);
}
}
// 释放链表内存
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
return 0;
}
// 创建一个双向链表节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// 在指定位置插入一个整数到双向链表中
Node* insertNode(Node* head, int position, int data) {
Node* newNode = createNode(data);
if (head == NULL) {
// 空链表,直接将新节点作为头节点
head = newNode;
} else if (position == 1) {
// 在头部插入新节点
newNode->next = head;
head->prev = newNode;
head = newNode;
} else {
// 在指定位置插入新节点
Node* current = head;
int count = 1;
while (count < position - 1 && current->next != NULL) {
current = current->next;
count++;
}
if (count == position - 1) {
newNode->next = current->next;
newNode->prev = current;
if (current->next != NULL) {
current->next->prev = newNode;
}
current->next = newNode;
}
}
return head;
}
// 从指定位置删除一个整数
Node* deleteNode(Node* head, int position) {
if (head == NULL) {
// 空链表,无需删除
return head;
}
if (position == 1) {
// 删除头节点
Node* temp = head;
head = head->next;
if (head != NULL) {
head->prev = NULL;
}
free(temp);
} else {
// 删除指定位置节点
Node* current = head;
int count = 1;
while (count < position && current != NULL) {
current = current->next;
count++;
}
if (count == position && current != NULL) {
current->prev->next = current->next;
if (current->next != NULL) {
current->next->prev = current->prev;
}
free(current);
}
}
return head;
}
// 打印双向链表中的所有元素
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
0.0分
0 人评分
C二级辅导-公约公倍 (C语言代码)浏览:1508 |
C语言训练-求函数值 (C语言代码)浏览:931 |
大神老白 (C语言代码)浏览:642 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:965 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:513 |
C语言程序设计教程(第三版)课后习题9.8 (C语言代码)浏览:606 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:542 |
求圆的面积 (C语言代码)浏览:1669 |
格式化数据输出 (C语言代码)浏览:821 |
良心推荐——>题解1049:C语言程序设计教程(第三版)课后习题11.1 (C语言描述——简单明了,时间复杂度低)浏览:1286 |