题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解法一
题目已经有提示了,首先我们用迭代来解决这个问题
(1)新建两个指针,一个指针是prev,代表前指针,最初指向none;一个指针是cur,代表当前指针,最初指向head
(2)存储cur的下一指针tmp,cur指向前指针prev,然后prev和cur都向后移动一位,如此遍历到空即可
代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
cur = head
while cur != None:
tmp = cur.next
cur.next = prev
prev = cur
cur = tmp
return prev
时间复杂度:O(n)
空间复杂度:O(1)
奥利给!
解法二:
第二种解法当然就是递归的解法,递归解法不太好理解;主要思路就是 先找到最后一个非空节点返回,然后上一个非空节点下一节点指向当前节点,当前节点指向空,一次递归,然后返回最后一个非空节点。
代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
cur = self.reverseList(head.next)
head.next.next = head
head.next = None
return cur
时间复杂度:O(n)
空间复杂度:O(n)
奥利给!