翻转单链表

来源:互联网 发布:linux chmod命令详解 编辑:程序博客网 时间:2024/05/06 10:15
#include <iostream>#include <malloc.h>struct Node{int val;Node* pNext;};Node* CreateLinkedNode(int num){Node* pHead = (Node*)malloc(sizeof(Node));pHead->pNext = NULL;for (int i = 0; i < num; ++i){Node* pNewNode = (Node*)malloc(sizeof(Node));pNewNode->val = i;pNewNode->pNext = pHead->pNext;pHead->pNext = pNewNode;}return pHead;}void PrintNode(Node* pHead){if (NULL == pHead){return;}Node* pNode = pHead->pNext;while (pNode){printf("%d ", pNode->val);pNode = pNode->pNext;}printf("\n");}Node* ReverseNode(Node* pHead){if (NULL == pHead){return NULL;;}Node* pReverseHead = NULL;Node* pNode = pHead->pNext;Node* pPre = NULL;while (pNode){Node* pNext = pNode->pNext;if (NULL == pNext){pReverseHead = pNode;}pNode->pNext = pPre;pPre = pNode;pNode = pNext; }pHead->pNext = pReverseHead;return pHead;}int main(){Node* pHead = CreateLinkedNode(10);PrintNode(pHead);pHead = ReverseNode(pHead);PrintNode(pHead);}

0 0
原创粉丝点击