数据结构和算法【C语言】---单链表

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

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

PNODE CreateNode(int data)
{
	PNODE pNew = (Node *)malloc(sizeof(Node));
	pNew->data = data;
	pNew->pNext = NULL;
	return pNew;
}

List CreateList(int src[], int length)
{
	int i = 0;
	PNODE pHead = CreateNode(-1);
	PNODE p = pHead;
	for (i=0; i<length;i++)
	{
		PNODE pNew = CreateNode(src[i]);
		p->pNext = pNew;
		p = p->pNext;
	}
	return pHead;
}

void Append(List pHead, int val)
{
	PNODE p = pHead;
	while (p->pNext)
	{
		p = p->pNext;
	}
	p->pNext = CreateNode(val);
}

int Insert(List pHead, int pos, int val)
{
	int i;
	PNODE p;
	PNODE pNew;
	if (pHead == NULL || pos < 1)
		return -1;

	p = pHead;
	for (i=1; i< pos; i++)
	{
		if (p == NULL)
		{
			return -1;
		}
		p = p->pNext;
	}

	pNew = CreateNode(val);
	pNew->pNext = p->pNext;
	p->pNext = pNew;

	return 0;
}

int Delete(List pHead, int data)
{
	PNODE pPrev;
	PNODE pCurr;

	if (pHead == NULL || pHead->pNext == NULL)
		return -1;

	if (pHead->data == data)
	{
		Node *p = pHead;
		pHead = pHead->pNext;
		free(p);
		p = NULL;
	}

	pPrev = pHead;
	pCurr = pHead->pNext;

	while (pCurr != NULL)
	{
		if (pCurr->data == data)
		{
			pPrev->pNext = pCurr->pNext;
			free(pCurr);
			pCurr = NULL;
			return 0;
		}
		pPrev = pCurr;
		pCurr = pCurr->pNext;
	}
	return -1;
}

void Print(List pHead)
{
	PNODE p;
	if (pHead == NULL)
	{
		return;
	}
	p = pHead->pNext;
	while (p != NULL)
	{
		printf("%d ", p->data);
		p = p->pNext;
	}
	printf("\n");
}

void main()
{
	int temp[] = { 7,1,3,9,6,4,3,6,2 };
	List pHead = CreateList(temp, sizeof(temp) / sizeof(int));
	Print(pHead);
	Insert(pHead, 1, 10);
	Insert(pHead, 8, 0);
	Print(pHead);
	Append(pHead,11);
	Print(pHead);
	Delete(pHead, 9);
	Delete(pHead, 1);
	Delete(pHead, 11);
	Print(pHead);

	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值