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:
def reverseList(self, head):
if head is None or head.next is None:
return head
prev, cur, nxt = None, head, head
while cur is not None:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
主要就是找好prev, cur, nxt的位置,prev先设为None,这个也算一个小细节。