c++单链表的基本操作代码
时间: 2023-12-30 11:19:56 浏览: 87
单链表的基本操作代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化链表
void init(Node** head) {
*head = NULL;
}
// 头节点后插入
void insert(Node** head, int x) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = *head;
*head = newNode;
}
// 在第k个节点后插入
void insertAfter(Node* prevNode, int x) {
if (prevNode == NULL) {
printf("The given previous node cannot be NULL");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = prevNode->next;
prevNode->next = newNode;
}
// 删除第k个节点
void remove(Node** head, int k) {
if (*head == NULL) {
printf("The list is empty");
return;
}
Node* temp = *head;
if (k == 0) {
*head = temp->next;
free(temp);
return;
}
for (int i = 0; temp != NULL && i < k - 1; i++)
temp = temp->next;
if (temp == NULL || temp->next == NULL) {
printf("The given position is invalid");
return;
}
Node* nextNode = temp->next->next;
free(temp->next);
temp->next = nextNode;
}
// 输出链表
void display(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* head;
init(&head);
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insertAfter(head->next, 4);
remove(&head, 2);
display(head);
return 0;
}
```
阅读全文