C语言链表基本操作请用代码展示
时间: 2023-05-11 10:02:40 浏览: 142
以下是 C 语言链表的基本操作代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾插入节点
void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
// 在链表头部插入节点
void insertAtBeginning(Node** head, int data) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// 在指定位置插入节点
void insertAtPosition(Node** head, int data, int position) {
Node* newNode = createNode(data);
if (position == 1) {
newNode->next = *head;
*head = newNode;
return;
}
Node* curr = *head;
for (int i = 1; i < position - 1 && curr != NULL; i++) {
curr = curr->next;
}
if (curr == NULL) {
printf("Invalid position\n");
return;
}
newNode->next = curr->next;
curr->next = newNode;
}
// 删除指定节点
void deleteNode(Node** head, int data) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* curr = *head;
while (curr->next != NULL && curr->next->data != data) {
curr = curr->next;
}
if (curr->next == NULL) {
printf("Node not found\n");
return;
}
Node* temp = curr->next;
curr->next = curr->next->next;
free(temp);
}
// 打印链表
void printList(Node* head) {
if (head == NULL) {
printf("List is empty\n");
return;
}
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtBeginning(&head, 0);
insertAtPosition(&head, 4, 4);
deleteNode(&head, 3);
printList(head);
return 0;
}
```
注意:以上代码仅为示例,实际使用时需要根据具体需求进行修改和优化。
阅读全文