Leetcode 206. Reverse Linked List
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?
基础数据结构题
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
output = ListNode(0)
cur = head.next
head.next = output.next
output.next = head
while (cur != None):
a = cur.next
cur.next = output.next
output.next = cur
cur = a
return output.next
即使是基础人家怎么写得这么elegant呢
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
node = head
while node:
next = node.next
node.next = prev
prev = node
node = next
return prev