创建一个长度为n的双向链表,并输出 在双向链表的第i个结点之前插入一个新节点x,并输出插入后的结果 最后删除双链表的第j个结点,并输出删除后的结果(c语言)
时间: 2024-10-09 09:01:20 浏览: 29
在C语言中,你可以使用结构体定义双向链表节点,然后提供相应的函数来操作这个链表。以下是创建、插入和删除的操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
// 初始化空链表
Node* createList(int n) {
Node* head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i + 1;
newNode->prev = NULL;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
return head;
}
// 插入节点在第i个位置
void insertAtPosition(Node** head, int i, int x) {
if (i <= 0 || i > listLength(*head)) {
printf("Invalid index.\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->prev = (*head)->prev;
newNode->next = (*head);
if ((*head)->prev != NULL) {
(*head)->prev->next = newNode;
} else {
head = newNode; // 如果插入的是头节点
}
(*head)->prev = newNode;
}
// 删除第j个节点
void deleteNode(Node** head, int j) {
if (*head == NULL || j <= 0 || j > listLength(*head)) {
printf("Invalid index or empty list.\n");
return;
}
if (j == 1) { // 删除头节点
Node* temp = *head;
*head = (*head)->next;
free(temp);
} else {
Node* current = *head;
for (int i = 1; i < j && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Index out of range.\n");
return;
}
current->prev->next = current->next;
if (current->next != NULL) {
current->next->prev = current->prev;
}
free(current);
}
}
// 计算链表长度
int listLength(Node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
int n = 5;
Node* list = createList(n);
printf("Original list: ");
printList(list);
int i = 2, x = 10;
insertAtPosition(&list, i, x);
printf("After inserting at position %d: ", i);
printList(list);
int j = 3;
deleteNode(&list, j);
printf("After deleting node at position %d: ", j);
printList(list);
return 0;
}
```
这个示例中,`createList()`用于初始化一个长度为n的链表,`insertAtPosition()`插入新节点,`deleteNode()`删除指定位置的节点,`printList()`用于打印链表内容。注意,在实际应用中,你需要处理可能出现的各种边界条件和内存管理。
阅读全文