C语言 ----- 链表算法实现

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
	int data;
	struct Node * pNext;
}NODE,*PNODE;

PNODE create_list(void);
void traverse_list(PNODE);
bool is_empty(PNODE pHead);

int length_list(PNODE);
bool insert_list(PNODE, int, int);
bool delete_list(PNODE, int, int*); //int * 删除的数据
void sort_list(PNODE);


int main(void)
{
	PNODE pHead = NULL;
	pHead = create_list();
	traverse_list(pHead);
	//is_empty(pHead);
	//int len = length_list(pHead);
	//printf("链表长度:%d\n",len);
	//sort_list(pHead);
	//traverse_list(pHead);
	insert_list(pHead,3,222);
	traverse_list(pHead);

	int val;
	if(delete_list(pHead,2,&val)){
		printf("删除的结点是:%d\n",val);
	}
	else
	{
		printf("您删除的元素不存在!\n");
	}
	traverse_list(pHead);
	return 0;
}

PNODE create_list(void)
{
	int len;//有效节点个数
	int i;
	int val;//输入的值

	PNODE pHead = (PNODE)malloc(sizeof(NODE));
	if(NULL == pHead)
	{
		printf("分配失败,程序终止!\n");
		exit(-1);
	}
//尾结点
	PNODE pTail = pHead;
	pTail->pNext = NULL;


	printf("请您输入需要生成的链表节点的个数:len = ");

	scanf("%d",&len);

	for(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;
		pNew->pNext = NULL;
		pTail = pNew; //指向尾结点
	}

	return pHead;
}

void traverse_list(PNODE pHead)
{
	PNODE p = pHead->pNext;
	printf("遍历元素:");
	while(NULL != p)
	{
		printf("%d ",p->data);
		p = p->pNext;
	}

	printf("\n");
}

bool is_empty(PNODE pHead)
{
	if(NULL == pHead->pNext)
	{
		printf("链表为空!\n");
		return true;
	}
	else
	{
		printf("链表不为空!\n");
		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;

	for(i=0, p=pHead->pNext; i<len-1; i++,p=p->pNext)
	{
		for(j=i+1,q=p->pNext; j<len; j++)//q=p->pNext下一个元素
		{
			if(p->data > q->data)
			{
				t = p->data;
				p->data = q->data;
				q->data = t;
			}
			
		}
	}
}

bool insert_list(PNODE pHead, int pos, int val)
{
	int i = 0;
	PNODE p = pHead;

	//拿到<pos-1 前一个
	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;
	PNODE q;
	//拿到<pos-1 前一个,为了删除它后边的元素
	while(NULL!=p->pNext && i<pos-1)
	{
		p = p->pNext;
		i++;
	}

	//pos 可能为负值
	if(i>pos-1 || NULL==p->pNext)
	{
		return false;
	}

	
	q = p->pNext;
	*pVal = q->data;
	p->pNext = q->pNext;
	free(q);

	return true;
}

点赞