C语言单链表的创建、插入、查找、删除、求长、排序、遍历
程序员文章站
2022-05-06 09:45:32
...
1.定义链表节点
typedef struct Node
{
int data;
struct Node *pNext;
}NODE, *PNODE;
2.链表的创建
PNODE createList()
{
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (pHead == NULL)
{
printf("memory allocation failure!");
exit(-1);
}
pHead->pNext = NULL;
return pHead;
}
3.链表的插入-头插法
void instertNodeBehindTheHead(PNODE pHead, int data)
{
PNODE newNode = (PNODE)malloc(sizeof(NODE));
if (newNode == NULL)
{
printf("memory allocation failure!");
exit(-1);
}
newNode->data = data;
newNode->pNext = pHead->pNext;
pHead->pNext = newNode;
}
4. 链表的查找
PNODE findNode(PNODE pHead, int dfind)
{
pHead = pHead->pNext;
while (pHead)
{
if (pHead->data == dfind)
{
break;
}
pHead = pHead->pNext;
}
return pHead;
}
5.链表的删除
void deleteNode(PNODE pHead, PNODE pDelete)
{
while (pHead->pNext != pDelete)
{
pHead = pHead->pNext;
}
pHead->pNext = pDelete->pNext;
free(pDelete);
pDelete = NULL;
}
6.链表的求长
int lengthOfList(PNODE pHead)
{
pHead = pHead->pNext;
int len = 0;
while (pHead)
{
len++;
pHead = pHead->pNext;
}
return len;
}
7.链表的排序-冒泡法,可以优化为不交换数据而交换指针
void popSortList(PNODE pHead)
{
int len = lengthOfList(pHead);
PNODE t;
for (int i = 0; i < len-1; i++)
{
t = pHead->pNext;
for (int j = 0; j < len-1-i; j++)
{
if (t->data > t->pNext->data)
{
t->data ^= t->pNext->data;
t->pNext->data ^= t->data;
t->data ^= t->pNext->data;
}
t = t->pNext;
}
}
}
8.链表的遍历
void traverseList(PNODE pHead)
{
pHead = pHead->pNext;
while (pHead)
{
printf("%d ", pHead->data);
pHead = pHead->pNext;
}
printf("\n");
}
9. 主函数
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
int main()
{
srand((unsigned int)time(NULL));
PNODE pHead = createList();
for (int i = 0; i < 10; i++)
{
int data = rand() % 255;
instertNodeBehindTheHead(pHead, data);
}
int len = lengthOfList(pHead);
printf("length of list = %d\n", len);
traverseList(pHead);
PNODE pFind = findNode(pHead, 109);
if (pFind == NULL)
{
printf("no find!\n");
}
else
{
printf("find!\n");
deleteNode(pHead, pFind);
printf("********************delete******************\n");
traverseList(pHead);
}
popSortList(pHead);
printf("********************after******************\n");
traverseList(pHead);
system("pause");
return 0;
}
10. 运行结果
上一篇: Bootstrap框架----弹出层录入
下一篇: C语言---实现单链表的插入和删除操作
推荐阅读
-
史上“最强”单链表实现(插入,删除,查找,求长...你想要的这里都有!)
-
单链表创建、删除、查找、插入之C语言实现
-
C语言单链表的创建、插入、查找、删除、求长、排序、遍历
-
C语言进阶-第18讲:单链表的遍历、创建、插入和删除结点
-
单链表的创建,删除,插入,查找及源码(c++实现)
-
C语言单链表创建,插入,删除,遍历
-
史上“最强”单链表实现(插入,删除,查找,求长...你想要的这里都有!)
-
数据结构(C语言):双向链表的创建、插入、修改、删除、查找、修改等操作
-
数据结构(c语言版)---- 双向循环链表的创建、插入、删除、遍历等基本操作
-
数据结构基础--单链表的基本操作(创建,插入,删除和查找)C++