标签:net ever 反转 csdn list blog 参考 输入 剑指offer
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* ReverseList(ListNode* pHead) { 12 ListNode *pre = NULL, *cur = pHead, *next = NULL; 13 while (cur != NULL) { //cur从表头开始,直到表尾 14 next = cur->next; //先用一个指针指向cur的下一个节点 15 cur->next = pre; //cur指向pre 16 pre = cur; //pre指向cur 17 cur = next; //cur指向next 18 } 19 return pre; 20 } 21 };
二、递归解法
参考https://blog.csdn.net/FX677588/article/details/72357389
1 ListNode* ReverseList(ListNode* pHead) { 2 if (pHead == NULL || pHead->next == NULL) { 3 return pHead; 4 } else { 5 ListNode *newHead = ReverseList(pHead->next); //先反转后面的链表 6 pHead->next->next = pHead; //反转当前节点与下一节点 7 pHead->next = NULL; // 8 return newHead; 9 } 10 }
标签:net ever 反转 csdn list blog 参考 输入 剑指offer
原文地址:https://www.cnblogs.com/qinduanyinghua/p/10599232.html