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);
}