单链表的头尾插入和删除C语言
时间: 2023-11-05 14:04:38 浏览: 82
c实现单链表插入和删除
单链表的头尾插入和删除C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 头插法插入节点
void insertAtHead(Node** headRef, int newData) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = newData;
newNode->next = *headRef;
*headRef = newNode;
}
// 尾插法插入节点
void insertAtTail(Node** headRef, int newData) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = newData;
newNode->next = NULL;
if (*headRef == NULL) {
*headRef = newNode;
return;
}
Node* lastNode = *headRef;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
// 头删除节点
void deleteAtHead(Node** headRef) {
if (*headRef == NULL) {
return;
}
Node* tempNode = *headRef;
*headRef = tempNode->next;
free(tempNode);
}
// 尾删除节点
void deleteAtTail(Node** headRef) {
if (*headRef == NULL) {
return;
}
Node* lastNode = *headRef;
Node* prevNode = NULL;
while (lastNode->next != NULL) {
prevNode = lastNode;
lastNode = lastNode->next;
}
if (prevNode == NULL) {
*headRef = NULL;
} else {
prevNode->next = NULL;
}
free(lastNode);
}
// 打印链表
void printList(Node* head) {
Node* tempNode = head;
while (tempNode != NULL) {
printf("%d ", tempNode->data);
tempNode = tempNode->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 头插法插入节点
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtHead(&head, 3);
printf("After head insert: ");
printList(head);
// 头删除节点
deleteAtHead(&head);
printf("After head delete: ");
printList(head);
// 尾插法插入节点
insertAtTail(&head, 4);
insertAtTail(&head, 5);
insertAtTail(&head, 6);
printf("After tail insert: ");
printList(head);
// 尾删除节点
deleteAtTail(&head);
printf("After tail delete: ");
printList(head);
return 0;
}
```
阅读全文