郝斌老师-数据结构-链表存储
老师所用的排序方法,好像是一种名为交换排序的方法,类似与冒泡。本想改成正统的冒泡,但在网络上找了一圈,要么是错的,要么太过麻烦,难懂。
希望有好心人能在评论区,贴上正统的链表冒泡代码链接。好人一生平安!
#include <bits/stdc++.h>
typedef struct Node
{
int data; //数据域
struct Node *pNext; //指针域
} NODE, *PNODE;
//函数声明
PNODE create_list();
void traverse_list(PNODE pHead);
bool is_empty(PNODE pHead);
int length_list(PNODE pHead);
bool insert_list(PNODE pHead, int pos, int val);
bool delete_list(PNODE pHead, int pos, int *pVal);
void sort_list(PNODE pHead);
int main()
{
PNODE pHead = NULL; //等价于 struct Node * pHead = NULL;
pHead = create_list(); //创建一个非循环单链表,并将该链表头节点地址赋给pHead
traverse_list(pHead);
// sort_list(pHead);
int val;
delete_list(pHead, 4, &val);
// insert_list(pHead, 4, 33);
traverse_list(pHead);
return 0;
}
PNODE create_list()
{
int len; //用来存放有效节点的个数
int val; //用来存放用户输入的节点的值
//分配一个不存放数据的头节点
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("分配失败,程序终止!\n");
exit(-1);
}
//生成一个永远指向尾节点的指针pTail
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入您需要生成链表节点的个数:len = ");
scanf("%d", &len);
for (int i = 0; i < len; i++)
{
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &val);
//每循环一次,都生成一个节点,将其挂载到链表上
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("分配失败,程序终止!\n");
exit(-1);
}
pNew->data = val;
//连接上一个节点
pTail->pNext = pNew;
//尾节点赋NULL
pNew->pNext = NULL;
//指向尾节点
pTail = pNew;
}
return pHead;
}
//遍历
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
//第一次判断pHead-Next是否为空
//当p->pNext为NULL结束
while (NULL != p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
//判断列表是否为空
bool is_empty(PNODE pHead)
{
if (NULL == pHead->pNext)
return true;
else
return false;
}
//求链表的长度
int length_list(PNODE pHead)
{
PNODE p = pHead->pNext;
int len = 0;
while (NULL != p)
{
len++;
p = p->pNext;
}
return len;
}
//排序链表
void sort_list(PNODE pHead)
{
int i, j, t;
int len = length_list(pHead);
PNODE p, q;
// p为首个有效数
for (i = 0, p = pHead->pNext; i < len - 1; i++, p = p->pNext)
{
for (j = i, q = p->pNext; j < len - 1; j++, q = q->pNext)
{
if (p->data > q->data)
{
t = q->data;
q->data = p->data;
p->data = t;
}
}
}
return;
}
//再pHead所指向链表的第pos个节点的前面插入一个新的节点,该节点的值是val,并且pos的值从1开始
bool insert_list(PNODE pHead, int pos, int val)
{
int i = 0;
PNODE p = pHead;
while (NULL != p && i < pos - 1)
{
p = p->pNext;
++i;
}
if (i > pos - 1 || NULL == p)
{
return false;
}
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("动态分配内失败!\n");
exit(-1);
}
pNew->data = val;
PNODE q = p->pNext;
p->pNext = pNew;
pNew->pNext = q;
return true;
}
bool delete_list(PNODE pHead, int pos, int *pVal)
{
int i = 0;
PNODE p = pHead;
while (NULL != p->pNext && i < pos - 1)
{
p = p->pNext;
++i;
}
if (i > pos - 1 || NULL == p->pNext)
{
return false;
}
PNODE q = p->pNext;
*pVal = q->data;
//删除
p->pNext = p->pNext->pNext;
free(q);
q = NULL;
return true;
}