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