leetcode: 206. Reverse Linked List
阿新 • • 發佈:2019-01-01
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