LeetCode#206 Reverse Linked List
Problem Definition:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution 1: 找到最后一个节点作为起始节点,头插。
def reverseList(head): if head==None: return head tail=head while tail.next!=None: tail=tail.next while head!=tail: hn=head.next head.next=tail.next tail.next=head head=hn return tail
Solution 2: 遍历直接反转。
1 def reverseList(self, head): 2 if head==None: 3 return head 4 p=head.next 5 head.next=None 6 while p!=None: 7 tmp=p.next 8 p.next=head 9 head=p 10 p=tmp 11 return head
Solution 3:递归。把Solution 2的循环改成递归实现。
1 def reverseList(head): 2 if head==None: 3 return head 4 p=head.next 5 head.next=None 6 return recursive(head,p) 7 def recursive(head,p): 8 if p==None: 9 return head 10 tmp=p.next 11 p.next=head 12 return recursive(p,tmp)

浙公网安备 33010602011771号