题目描述:
输入一个链表,反转链表后,输出新链表的表头。
1. 非递归方法:
思路:
比如1->2->3->4,遍历链表,把1的next置为None,2的next置为1,以此类推,4的next置为3,得到1<-2<-3<-4,即4->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):
# write code here
if not pHead or not pHead.next:
return pHead
pre,cur = None,pHead
while cur:
cur.next,cur,pre = pre,cur.next,cur
return pre
递归方法:
思路:
通过递归走到最后一个节点,然后更新每个节点的next值。
代码如下:
# -*- 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 not pHead or not pHead.next:
return pHead
node = self.ReverseList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return node