欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

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