链表反转

来源:互联网 发布:金坷垃 知乎 编辑:程序博客网 时间:2024/05/01 21:13
#include <stdio.h>struct Node{int data;struct Node *pNext;};void print_List(struct Node *pHead){struct Node *pNode = pHead;while (pNode){printf("%d, ", pNode->data);pNode = pNode->pNext;}printf("\n");}struct Node* ReverseList(struct Node *pHead){struct Node *pReverseHead = NULL;struct Node *pTmp = NULL;struct Node *pPrev = NULL;struct Node *pNode = pHead;while (pNode){if (pNode->pNext == NULL)pReverseHead = pNode;pTmp = pNode->pNext;pNode->pNext = pPrev;pPrev = pNode;pNode = pTmp;}return pReverseHead;}void main(){int nodeSize = 10;struct Node *pHead = (struct Node*)malloc(nodeSize * sizeof(struct Node));struct Node *pNode = pHead;int len = nodeSize;while (len--){pNode->data = len+100;pNode->pNext = pNode+1;if (0 == len) pNode->pNext = NULL;pNode = pNode->pNext;}print_List(pHead);struct Node *pReverseHead = ReverseList(pHead);print_List(pReverseHead);struct Node *pNodeFree = pHead;struct Node *pNodeNext = NULL;while (pNodeFree){pNodeNext = pNodeFree->pNext;free(pNodeFree);pNodeFree = pNodeNext;}}