登录 注册

链表的递归操作

收藏
[C] 标签:链表,递归 2013-05-16 17:45
原始代码 全屏查看 0评 / 0藏 / 5297阅  跳至 / 152行
#include <stdio.h>
#include <stdlib.h>

typedef int DT;
typedef struct node
{
	DT data;
	struct node * pNext;
} Node, * pNode;

pNode CreateList(void);
void DelelteList(pNode);
void DeleteByData(pNode, DT);
void DeleteByIndex(pNode, int);
DT FindDataByIndex(pNode pCurr, int index);
void Insert(pNode, int, DT);
void PrintList(pNode);
void UpdateByIndex(pNode, int, DT);


int main(void)
{
	pNode pHead = CreateList();

	Insert(pHead, 0, 134);
	Insert(pHead, 1, 345);
	Insert(pHead, 2235, 234);
	PrintList(pHead);

	Insert(pHead, 222220, 285);
	PrintList(pHead);

	DeleteByIndex(pHead, 2);
	PrintList(pHead);
	//DeleteByIndex(pHead, 2345);
	//DeleteByIndex(pHead, 1);
	//DeleteByIndex(pHead, 1);
	//DeleteByIndex(pHead, 1);
	//PrintList(pHead);

	//DeleteByData(pHead, 285);
	//PrintList(pHead);
	//DeleteByData(pHead, 34444);
	//PrintList(pHead);

	UpdateByIndex(pHead, 2, 3333);
	PrintList(pHead);

	printf("%d\n", FindDataByIndex(pHead, 3));
	DelelteList(pHead);

	return 0;
}

pNode CreateList()
{
	pNode pHead = (pNode)malloc(sizeof(Node));
	pHead->pNext = NULL;
	return pHead;
}

void DelelteList(pNode pCurr)
{
	if (pCurr != NULL)
	{
		pNode pTemp = pCurr;
		pCurr = pCurr->pNext;
		free(pTemp);
		DelelteList(pCurr);
	}
}

// 想插入到链表结尾,给index赋以不溢出的大值即可
void Insert(pNode pCurr, int index, DT data)
{
	static int i = 0;
	if ((index == i++) || (pCurr == NULL) || (pCurr->pNext == NULL))
	{
		pNode pNew = (pNode)malloc(sizeof(Node));
		pNew->data = data;
		pNew->pNext = pCurr->pNext;
		pCurr->pNext = pNew;
		i = 0;
	}
	else
		Insert(pCurr->pNext, index, data);
}

// 索引不正确时会返回-1
DT FindDataByIndex(pNode pCurr, int index)
{
	static int i = 1;
	if (pCurr->pNext == NULL)
		return -1;
	if (index == i++)
	{
		return pCurr->pNext->data;
	}
	else
		FindDataByIndex(pCurr->pNext, index);
}

void UpdateByIndex(pNode pCurr, int index, DT data)
{
	DeleteByIndex(pCurr, index);
	Insert(pCurr, index - 1, data);
}

void DeleteByIndex(pNode pCurr, int index)
{
	static int i = 1;
	if ((0 >= index) || (pCurr == NULL) || (pCurr->pNext == NULL))
		return;
	if (index == i++)
	{
		pNode pTemp = pCurr->pNext;
		pCurr->pNext = pCurr->pNext->pNext;
		free(pTemp);
	}
	else
		DeleteByIndex(pCurr->pNext, index);
	i = 1;
}

void DeleteByData(pNode pCurr, DT data)
{
	if((pCurr == NULL) || (pCurr->pNext == NULL))
		return;
	if(pCurr->pNext->data == data)
	{
		pNode pTemp = pCurr->pNext;
		pCurr->pNext = pCurr->pNext->pNext;
		free(pTemp);
	}
	DeleteByData(pCurr->pNext, data);
}

void PrintList(pNode pCurr)
{
	if (pCurr == NULL)
		return;
	if (pCurr->pNext != NULL)
	{
		printf("%d\t", pCurr->pNext->data);
		PrintList(pCurr->pNext);
	}
	else
	{
		printf("\n");	
		return;
	}
}

最新评论

  · · · · · ·  (共0条)

目前还没有评论

登录后您才可以发表评论。 马上登录 立即注册
夜丶未央
2013-05-16加入
夜丶未央最近分享的代码
Back to Top