首页 > 学院 > 开发设计 > 正文

c语言用尾递归实现单向链表的逆向排列

2019-11-10 18:05:46
字体:
来源:转载
供稿:网友

c++的stl很好用,c语言的简单链表最近几年几乎不用了。最近一次笔试,遇到了这题,就十分捉急。当时想到似乎得用递归。现在算是完成了。

以下以简单的单向链表(链表头结点跟普通结点一致)为例。

#include <stdlib.h>typedef struct Node {	int i;	struct Node *pNext;} Node;Node *createList(const int *datas, unsigned numOfData);Node *reverseList(Node *pList);int main() {	int datas[4] = { 1, 3, 0, -78 };	Node *pList = createList(datas, sizeof(datas) / sizeof(int));	Node *pList2 = reverseList(pList);	return 0;}Node *createList(const int *datas, unsigned numOfData) {	Node *pTmp = NULL;	Node *pLast = NULL;	Node *pHead = NULL;	const size_t sizeOfNode = sizeof(Node);	pHead = (Node*)malloc(sizeOfNode);	pHead->i = datas[0];	pLast = pHead;	for (unsigned i = 1; i < numOfData; i++) {		pTmp = (Node*)malloc(sizeOfNode);		pTmp->i = datas[i];		pLast->pNext = pTmp;		pLast = pTmp;	}	pLast->pNext = NULL;	return pHead;}Node *reverseNode(Node *pCur, Node *pPRe) {	Node *pNext = pCur->pNext;	pCur->pNext = pPre;	if (pNext == NULL) {		return pCur;	}	return reverseNode(pNext, pCur);}Node *reverseList(Node *pList) {	return reverseNode(pList, NULL);}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表