编写程序,实现单链表的基本操作:初始化、建表(头插法或尾插法)、查找、插入、删除、求表长。C语言
时间: 2023-11-08 16:59:12 浏览: 145
可以通过以下代码实现单链表的基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域,指向下一个节点
} Node;
// 初始化链表
void initLinkedList(Node** head) {
*head = NULL;
}
// 头插法建表
void createLinkedListHead(Node** head) {
int data;
printf("输入节点数据,输入-1结束:");
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
}
// 尾插法建表
void createLinkedListTail(Node** head) {
int data;
printf("输入节点数据,输入-1结束:");
Node* tail = NULL;
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
}
// 查找节点
Node* findNode(Node* head, int target) {
Node* p = head;
while (p != NULL) {
if (p->data == target) {
return p;
}
p = p->next;
}
return NULL;
}
// 插入节点
void insertNode(Node** head, int pos, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (pos == 0) {
newNode->next = *head;
*head = newNode;
return;
}
Node* p = *head;
int count = 0;
while (p != NULL && count < pos - 1) {
p = p->next;
count++;
}
if (p == NULL) {
printf("位置无效!\n");
return;
}
newNode->next = p->next;
p->next = newNode;
}
// 删除节点
void deleteNode(Node** head, int data) {
Node* p = *head;
Node* prev = NULL;
// 删除的是头节点
if (p != NULL && p->data == data) {
*head = p->next;
free(p);
return;
}
while (p != NULL && p->data != data) {
prev = p;
p = p->next;
}
if (p == NULL) {
printf("未找到要删除的节点!\n");
return;
}
prev->next = p->next;
free(p);
}
// 求表长
int getLength(Node* head) {
int len = 0;
Node* p = head;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
// 打印链表
void printLinkedList(Node* head) {
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* head;
initLinkedList(&head);
createLinkedListTail(&head);
printLinkedList(head);
int target;
printf("输入要查找的节点数据:");
scanf("%d", &target);
Node* result = findNode(head, target);
if (result != NULL) {
printf("找到了!\n");
} else {
printf("未找到!\n");
}
int pos, data;
printf("输入要插入的位置和数据:");
scanf("%d %d", &pos, &data);
insertNode(&head, pos, data);
printLinkedList(head);
printf("输入要删除的节点数据:");
scanf("%d", &target);
deleteNode(&head, target);
printLinkedList(head);
int length = getLength(head);
printf("链表长度:%d\n", length);
return 0;
}
```
阅读全文