題目描述:
翻轉一個鏈表
樣例
給出一個鏈表1->2->3->null,這個翻轉后的鏈表為3->2->1->null
挑戰
在原地一次翻轉完成
題目分析:
在原地一次翻轉完成
循環head鏈表,將鏈表中的元素從表頭依次取出指向新鏈表即可。
源碼:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place.
"""
def reverse(self, head):
# write your code here
if head is None: return None
p = head
cur = None
pre = None
while p is not None:
cur = p.next
p.next = pre
pre = p
p = cur
return pre
