应用c语言双向链实现初始化,生成线性表3 55 2 9 7 32 66,遍历输出线性表并给出表长;将你学号后三位数值插入到第3个位置,遍历输出线性表并给出表长;将第5个元素删除,遍历输出线性表,给出表长和被删除元素;销毁线性表,显示销毁结果
时间: 2024-10-09 11:08:40 浏览: 35
在C语言中,我们可以使用双向链表(Doubly Linked List)来实现线性表的初始化、插入、删除以及遍历操作。这里是一个简单的示例来满足您的需求:
首先,我们创建一个双向链表节点结构体:
```c
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
```
1. 初始化线性表并遍历输出:
```c
Node* initList(int arr[], int size) {
Node* head = NULL, *tail = NULL;
for (int i = 0; i < size; ++i) {
Node* newNode = malloc(sizeof(Node));
newNode->data = arr[i];
newNode->prev = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
printf("%d ", newNode->data);
}
printf("\n");
return head;
}
// 遍历输出
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
```
2. 插入后三位数到第3个位置,并遍历输出:
```c
void insertAfterNode(Node* head, int index, int value) {
Node* newNode = malloc(sizeof(Node));
newNode->data = value;
newNode->prev = head;
newNode->next = head->next;
if (index == 0) {
newNode->next->prev = newNode;
head = newNode;
} else {
Node* current = head->next;
for (int i = 1; i < index - 1 && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->prev = current->prev;
newNode->next = current;
current->prev->next = newNode;
current->prev = newNode;
}
}
// 输出新表
printList(head);
}
// 给定例子:学号后三位数值设为123
insertAfterNode(head, 3, 123);
```
3. 删除第5个元素,遍历输出并计算表长:
```c
void deleteElement(Node** head, int index) {
if (*head == NULL) return;
if (index == 0) {
Node* temp = *head;
*head = *head->next;
free(temp);
} else {
Node* current = *head;
for (int i = 1; i < index && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
current->prev->next = current->next;
if (current->next != NULL) {
current->next->prev = current->prev;
}
free(current);
}
}
// 输出新表
printList(*head);
int length = getLength(head);
printf("表长: %d\n", length);
// 计算表长辅助函数
int getLength(Node* head) {
int count = 0;
Node* temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
}
deleteElement(&head, 4); // 第5个元素是索引4
```
4. 销毁线性表(仅释放内存,无实际输出):
```c
void destroyList(Node* head) {
Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
destroyList(head); // 销毁线性表
```
注意:这个例子假设所有内存分配都能成功,实际情况需要考虑错误处理。此外,`getLength`函数可以合并到`deleteElement`中,以避免不必要的内存访问。
阅读全文