反转链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}
解题思路
- 使用栈
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead:
return pHead
result = []
wei = pHead
while wei.next:
result.append(wei)
wei = wei.next
tou = wei
while result:
wei.next = result.pop()
wei = wei.next
wei.next = None
return tou
- 使用两个指针,一快一慢,每次将快指针所指的结点作为头节点,后面跟着慢指针所指的结点。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead or pHead.next == None:
return pHead
low = pHead
fast = pHead.next
low.next = None
while fast.next:
tmp = fast.next
fast.next = low
low = fast
fast = tmp
fast.next = low
return fast
- 递归
难点:pHead.next.next = pHead, pHead.next=None
这里相当于两个结点间的循环换位。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next==None:
return pHead
cur = self.ReverseList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return cur