剑指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     }
原文地址:https://www.cnblogs.com/qinduanyinghua/p/10599232.html