用C语言生产双向链表,将其初始化,生成线性表3 55 2 9 7 32 66,遍历输出线性表并给出表长; 将你学号后三位数值插入到第3个位置,遍历输出线性表并给出表长; 将第5个元素删除,遍历输出线性表, 给出表长和被删除元素。 销毁线性表,显示销毁结果。
时间: 2024-10-09 14:09:27 浏览: 30
在C语言中,我们可以创建一个双向链表结构来实现这个功能。首先,我们需要定义一个节点结构体,包含数据域和指向前一个和后一个节点的指针:
```c
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
```
接下来,我们可以编写函数来初始化、操作、遍历和销毁链表:
1. 初始化链表:
```c
Node* initializeList(int arr[], int size) {
Node* head = NULL, *tail = NULL;
for (int i = 0; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->prev = NULL;
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
return head;
}
```
2. 遍历链表并输出长度:
```c
void printList(Node* head) {
int length = 0;
while (head) {
printf("%d ", head->data);
length++;
head = head->next;
}
printf("\nLength: %d\n", length);
}
// 插入元素
void insertAtThird(Node** head, int index, int value) {
if (index == 3) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->prev = (*head)->prev;
newNode->next = (*head);
if ((*head)->prev) {
(*head)->prev->next = newNode;
} else {
head = newNode;
}
(*head)->prev = newNode;
}
printList(*head);
}
// 删除元素
void deleteFifth(Node** head) {
if (*head && (*head)->next) {
Node* fifthElement = (*head)->next->next;
if (fifthElement) {
fifthElement->prev->next = fifthElement->next;
if (fifthElement->next)
fifthElement->next->prev = fifthElement->prev;
free(fifthElement);
}
}
printList(*head);
printf("Length after deletion: %d\n", getLength(*head));
}
// 获取链表长度
int getLength(Node* head) {
int length = 0;
while (head) {
length++;
head = head->next;
}
return length;
}
// 销毁链表
void destroyList(Node* head) {
Node* current = head;
while (current) {
Node* temp = current;
current = current->next;
free(temp);
}
head = NULL;
printf("List destroyed.\n");
}
```
以上就是使用C语言创建双向链表,完成指定操作以及销毁链表的示例。记得在实际程序中处理可能出现的边界条件和内存管理错误。
阅读全文