逆转单链表
问题
思路
cur = pre->next; post = cur=>next; cur->next = pre; cur = post;
代码
ListNode* reverseList(ListNode *root) { if (root == NULL) return root; ListNode *cur = root; ListNode *pre = NULL; ListNode *post = NULL; ListNode *revRoot = NULL; while (cur != NULL) { post = cur->next; if (post == NULL) revRoot = cur; cur->next = pre; pre = cur; cur = post; } return revRoot; }
完整执行
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int v) : val(v), next(NULL) {} }; ListNode* createList() { ListNode *root = new ListNode(0); ListNode *p1 = new ListNode(1); ListNode *p2 = new ListNode(2); ListNode *p3 = new ListNode(3); root->next = p1; p1->next = p2; p2->next = p3; return root; } ListNode* reverseList(ListNode *root) { if (root == NULL) return root; ListNode *cur = root; ListNode *pre = NULL; ListNode *post = NULL; ListNode *revRoot = NULL; while (cur != NULL) { post = cur->next; if (post == NULL) revRoot = cur; cur->next = pre; pre = cur; cur = post; } return revRoot; } void deleteList(ListNode *root) { ListNode *p = root; while(root != NULL) { p = root->next; delete(root); root = p; } } void tranverse(ListNode* root) { while(root != NULL) { cout << root->val << " "; root = root->next; } cout << endl; } int main() { ListNode *root = createList(); tranverse(root); root = reverseList(root); tranverse(root); deleteList(root); }
结果
0 1 2 3 3 2 1 0