c语言单链表的插入,删除,遍历,输出
时间: 2023-05-19 17:04:43 浏览: 101
C语言之单链表的插入、删除与查找
5星 · 资源好评率100%
C语言单链表的插入、删除、遍历、输出操作如下:
插入操作:
1. 在链表头部插入节点:
```c
struct Node {
int data;
struct Node* next;
};
void insertAtBeginning(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
```
2. 在链表尾部插入节点:
```c
void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
return;
}
```
3. 在链表中间插入节点:
```c
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
printf("The given previous node cannot be NULL");
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
```
删除操作:
1. 删除链表头部节点:
```c
void deleteAtBeginning(struct Node** head_ref) {
if (*head_ref == NULL) {
printf("The list is empty");
return;
}
struct Node* temp = *head_ref;
*head_ref = (*head_ref)->next;
free(temp);
}
```
2. 删除链表尾部节点:
```c
void deleteAtEnd(struct Node** head_ref) {
if (*head_ref == NULL) {
printf("The list is empty");
return;
}
if ((*head_ref)->next == NULL) {
free(*head_ref);
*head_ref = NULL;
return;
}
struct Node* temp = *head_ref;
while (temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
```
3. 删除链表中间节点:
```c
void deleteNode(struct Node** head_ref, int key) {
struct Node* temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("The key is not present in the list");
return;
}
prev->next = temp->next;
free(temp);
}
```
遍历操作:
```c
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
```
输出操作:
```c
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 6);
insertAtBeginning(&head, 7);
insertAtBeginning(&head, 1);
insertAtEnd(&head, 4);
insertAfter(head->next, 8);
printf("Created Linked list is: ");
printList(head);
deleteNode(&head, 1);
printf("\nLinked List after Deletion of 1: ");
printList(head);
deleteAtEnd(&head);
printf("\nLinked List after Deletion at End: ");
printList(head);
deleteAtBeginning(&head);
printf("\nLinked List after Deletion at Beginning: ");
printList(head);
return 0;
}
```
这是一个完整的单链表的插入、删除、遍历、输出的代码。
阅读全文