单链表的相关基本操作(查找、删除、插入、撤销、输出)
准备工作
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef int ElemType;
typedef struct node {
ElemType element;
struct node* link;
}Node;
typedef struct headerList {
Node* head;
int n;
}HeaderList;
带表头的单链表的初始化
Status Init(HeaderList* h) { //初始化一个空的带表头的单链表
h->head = (Node*)malloc(sizeof(Node));
if (!h->head)return ERROR;
h->head->link = NULL;
h->n = 0;
return OK;
}
插入运算,实现在下标i之后插入,似乎叫后插法?
Status Insert(HeaderList* h, int i, ElemType x) { //在ai之后插入新元素x
Node* p = h->head;
Node* q = (Node*)malloc(sizeof(Node));
if (i<-1 || i>h->n - 1)
return ERROR;
for (int j = 0; j <=i; j++)
p = p->link; //定位到ai
q->link = p->link;
q->element = x;
p->link = q;
h->n++; //链表元素个数+1
return OK;
}
删除运算
Status Delete(HeaderList* h, int i) { //删除下标为i的元素
Node* p = h->head;
Node* pre = p;
if (!h->n) return ERROR;
if (i<0 || i>h->n - 1) return ERROR;
for (int j = 0; j <= i; j++) {
pre = p;
p = p->link;
}
pre->link = p->link;
h->n--; //链表元素个数减一
free(p); //释放p的动态空间
return OK;
}
查找运算,将元素值赋给x
Status Search(HeaderList* h, int i, ElemType *x) { //实现函数查找,将ai的值通过x返回
Node* p = h->head;
if (i<0 || i>h->n - 1)
return ERROR;
for (int j = 0; j <= i; j++)
p = p->link;
*x = p->element;
return OK;
}
输出运算
void Output(HeaderList* h) { //输出函数
Node* p = h->head;
for (int i = 0; i < h->n; i++) {
p = p->link;
printf("%3d", p->element);
if (i % 5 == 4 && i != 1) {
printf("\n");
}
}
}
代码撤销运算,释放内存空间
void Destroy(HeaderList* h) {
Node* p, * q = h->head;
while (q->link) {
p = q->link;
free(q);
q = p;
}
printf("clear successfully!");
}
逆置运算,在函数内部定义了一个新链表,按照前插法,每次调用insert函数,最终输出单链表r
Status Reverse(HeaderList* h) { //带表头的单链表逆置
HeaderList r;
Init(&r);
Node* p;
p = h->head;
if (!h->n) return ERROR;
while (p->link) {
p = p->link;
Insert(&r, -1, p->element);
}
printf("逆置后的单链表为:\n");
Output(&r);
return OK;
}
单链表的降序算法
void Sort(HeaderList* h) { //返回一个降序的单链表
Node* p, * q;
Status temp;
for (p = h->head->link; p->link != NULL; p = p->link) {
for (q = p->link; q != NULL; q = q->link) {
if (p->element < q->element) {
temp = p->element;
p->element = q->element;
q->element = temp;
}
}
}
return;
}
测试函数的主函数
int main() {
HeaderList q;
Init(&q);
for (int i = 0; i < 10; i++)
Insert(&q, i - 1, i + 1);
int j;
Output(&q);
Sort(&q);
printf("降序排列:\n");
Output(&q);
Reverse(&q);
Search(&q, 5, &j);
printf("输出删除前下标为5的元素:");
printf("%d\n", j);
Delete(&q, 5);
Output(&q);
Search(&q, 5, &j);
printf("输出删除后下标为5的元素:");
printf("%d\n", j);
Destroy(&q); //清空函数
return 0;
}
只需要将代码逐块复制进编译器就能运行了呀!如果有什么问题,可以评论区指出,新手上路,请多指教。