C语言单链表的创建、插入、查找、删除、求长、排序、遍历

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. 运行结果






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值