用结构体和指针实现单链表的应用,具体包含:建立单链表、在单链表中查找指定元素、在单链表中插入指定元素、删除单链表某个元素。用C语言实现
时间: 2024-05-07 18:21:00 浏览: 14
好的,下面是单链表结构体和相关操作函数的实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 建立单链表
Node* createList() {
Node *head, *p, *q;
int n, num;
head = (Node*)malloc(sizeof(Node));
head->next = NULL;
q = head;
printf("请输入链表的长度:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第 %d 个元素:", i+1);
scanf("%d", &num);
p = (Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
// 查找指定元素
Node* search(Node* head, int x) {
Node* p = head->next;
while (p != NULL && p->data != x) {
p = p->next;
}
return p;
}
// 在指定位置插入元素
void insert(Node* head, int pos, int x) {
Node* p = head;
for (int i = 0; i < pos-1; i++) {
if (p->next == NULL) {
printf("插入位置不合法!\n");
return;
}
p = p->next;
}
Node* q = (Node*)malloc(sizeof(Node));
q->data = x;
q->next = p->next;
p->next = q;
printf("插入成功!\n");
}
// 删除指定元素
void del(Node* head, int x) {
Node* p = head;
while (p->next != NULL && p->next->data != x) {
p = p->next;
}
if (p->next == NULL) {
printf("要删除的元素不存在!\n");
return;
}
Node* q = p->next;
p->next = q->next;
free(q);
printf("删除成功!\n");
}
// 输出单链表
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* head = createList();
printf("链表中的元素为:");
printList(head);
int x;
printf("请输入要查找的元素:");
scanf("%d", &x);
Node* p = search(head, x);
if (p == NULL) {
printf("要查找的元素不存在!\n");
} else {
printf("要查找的元素在链表中的位置为:%p\n", p);
}
int pos, num;
printf("请输入要插入的位置和元素值:");
scanf("%d %d", &pos, &num);
insert(head, pos, num);
printf("插入后的链表为:");
printList(head);
printf("请输入要删除的元素:");
scanf("%d", &x);
del(head, x);
printf("删除后的链表为:");
printList(head);
return 0;
}
```