题目描述
输入一个链表,反转链表后,输出新链表的表头。
解法1:三指针交换
注意循环条件初始化过程中,可能出现的特殊情况,Python代码:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
# 初始化循环条件
if pHead is None:
return pHead
x = pHead.next
if x is None:
return pHead
y = x.next
if y is None:
x.next = pHead
pHead.next = None
return x
z = y.next
x.next = pHead
pHead.next = None
# 迭代,迭代结束标志是z指向None
while z is not None:
y.next = x
x = y
y = z
z = z.next
y.next = x
return y
解法2:递归
递归的思维方式可以总结为三点:终止条件,递归调用,逻辑处理
public ListNode reverseList(参数0) {
if (终止条件)
return;
逻辑处理(可能有,也可能没有,具体问题具体分析)
//递归调用
ListNode reverse = reverseList(参数1);
逻辑处理(可能有,也可能没有,具体问题具体分析)
}
在这里,递归的逻辑很简单
终止条件就是找到链表的末尾,然后开始反转
还没找到链表的末尾就继续递归
递归出来之后再做一下反转
实际上这种方法也用到了三个指针,自行体会
代码如下:
class ReverseListRecursion
{
public:
ListNode* temp;
ListNode* Reverse(ListNode* pHead)
{
if (pHead->next->next == nullptr) // 找到了链表的末尾,开始反转
{
temp = pHead->next;
temp->next = pHead;
pHead->next = nullptr;
return pHead;
}
ListNode* node = Reverse(pHead->next);
node->next = pHead;
pHead->next = nullptr;
return pHead;
}
ListNode* tureReturn(ListNode* pHead)
{
if (pHead == nullptr || pHead->next == nullptr) // 空链表或者只有一个节点的链表
{
return pHead;
}
pHead = Reverse(pHead);
return temp;
}
};