写出在不带头结点的单链表上第i位置删除和插入一个结点的算法(C语言
时间: 2024-10-20 10:12:56 浏览: 36
在不带头节点的单链表上,第i位置删除和插入操作的C语言算法可以这样实现:
### 删除第i个节点 (Delete Node at Position i)
```c
void deleteNode(struct Node** head, int i) {
if (*head == NULL || i <= 0) return; // 验证链表是否为空或索引越界
struct Node* temp = *head;
struct Node* prev = NULL;
if (i == 1) { // 如果是要删除头节点
*head = temp->next;
free(temp);
return;
}
for (int j = 1; temp != NULL && j < i; j++) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return; // 如果索引超出列表长度
prev->next = temp->next;
free(temp); // 释放要删除的节点
}
```
### 插入新节点到第i个位置 (Insert Node at Position i)
```c
void insertNodeAtPosition(struct Node** head, int i, int data) {
if (*head == NULL) { // 列表为空,直接插入作为头节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
*head = newNode;
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (i <= 0) { // 插入在头部
newNode->next = *head;
*head = newNode;
return;
}
struct Node* temp = *head;
for (int j = 1; j < i; j++) {
if (temp->next == NULL) {
printf("Error: Index out of range.\n");
return;
}
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
```
阅读全文