Leetcode刷题笔记19-反转链表

1. 题目

反转一个单链表。

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

2. 示例

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

3. 优答

python3 52ms

方法1:迭代

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        Iterative
        """
        if head == None:
            return head
        pre = head
        cur = head.next
        while cur != None:
            pre.next = cur.next
            cur.next = head
            head = cur
            cur = pre.next
        return head

s = Solution()
head = ListNode(0)
cur = head
for i in range(1, 10):
    node = ListNode(i)
    cur.next = node
    cur = node
head = s.reverseList(head)
print(head)     # 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> None
while (head != None):
    print(head.val, end=' ')
    head = head.next
# 9 8 7 6 5 4 3 2 1 0

方法2:递归

class Solution(object):
    def reverseList(self, head):
        if head is None:
            return None
        else:
            rev_rest = self.reverseList(head.next)
            current = rev_rest
            if current is None:
                return head
            while current and current.next is not None:
                current = current.next
            current.next = head
            head.next = None
            return rev_rest
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
s = Solution()
r1 = s.reverseList(n1)
print(r1.val)
print(r1.next.val)
print(r1.next.next.val)

递归2

def recurse(head, newhead):  # 递归,head为原链表的头结点,newhead为反转后链表的头结点
    if head is None:
        return
    if head.next is None:
        newhead = head
    else:
        newhead = recurse(head.next, newhead)
        head.next.next = head
        head.next = None
    return newhead

head = ListNode(1)  # 测试代码
p1 = ListNode(2)  # 建立链表1->2->3->4->None
p2 = ListNode(3)
p3 = ListNode(4)
head.next = p1
p1.next = p2
p2.next = p3
newhead = None
p = recurse(head, newhead)  # 输出链表4->3->2->1->None
print(p)

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9167864.html