题目描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}
说明:本题目包含复杂数据结构ListNode,点此查看相关信息
1.迭代(双指针)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
#非递归方法,迭代(双指针)
#采用头插法将链表元素依次插入到pre表
pre = None
cur = pHead
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
return pre
2.递归
# -*- 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 not pHead.next:#链表为空或只有头结点
return pHead
headNode = self.ReverseList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return headNode