删除线性表中的第i个元素,并对删除该元素后的线性表进行打印输出;(使用C语言链表)
时间: 2024-11-03 10:22:57 浏览: 30
在C语言中,如果你已经有一个动态链表并且想要删除其中的第i个元素,你需要首先找到这个位置的前一个节点,然后将它的`next`指针指向第i+1个节点。这里是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 删除指定位置的节点
void deleteNode(Node** head, int position) {
if (*head == NULL || position <= 0) {
return; // 空链表或者位置无效直接返回
}
Node* current = *head;
Node* previous = NULL;
if (position == 1) { // 处理第一个节点的情况
*head = current->next;
} else {
for (int i = 1; i < position && current != NULL; i++) {
previous = current;
current = current->next;
}
if (current == NULL) {
return; // 未找到位置对应的节点
}
previous->next = current->next;
}
free(current); // 释放已删除节点的内存
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL; // 初始化链表为空
// ... (假设之前已经添加了节点)
int position;
printf("请输入要删除的位置(从1开始计数):");
scanf("%d", &position);
deleteNode(&head, position);
printList(head); // 删除后打印链表
return 0;
}
```
这段代码首先检查链表是否为空或给定的位置是否有效,然后遍历链表找到目标节点的位置,最后删除它并更新前一个节点的`next`指针。注意在删除节点之后要手动释放其内存以防止内存泄漏。
阅读全文
相关推荐

















