題目要求
反轉(zhuǎn)一個(gè)單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
思路一
遍歷給定鏈表,摘下節(jié)點(diǎn)放到新鏈表,新鏈表從后向前構(gòu)造
→_→ talk is cheap, show me the code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
new = None
while head:
p = head
head = head.next
p.next = new
new = p
return new