leetcode: 206. Reverse Linked List

Difficulty

Easy.

Problem

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

AC

class Solution():
    def reverseList(self, head):
        if not head:
            return head
        pre = dummy = ListNode(0)
        dummy.next = head
        cur = pre.next
        while cur.next:
            tmp = pre.next
            pre.next, cur.next, pre.next.next = cur.next, cur.next.next, tmp
        return dummy.next
Published 599 original articles · won praise 856 · Views 1.84 million +

Guess you like

Origin blog.csdn.net/JNingWei/article/details/83858121