單鏈表反轉-python實現

單鏈表反轉,可以使用 循環遞歸 兩種方式

  • 循環方式
class ListNode:
	def __init__(self, x):
		self.val = x
		self.next = None


def non_recurse(head):
	if head is None or head.next is None:
		return head
	prev = None
	cur = head
	new_head = head
	while cur:
		new_head = cur
		tmp = cur.next
		cur.next = prev
		prev = cur
		cur = tmp
	return new_head



head = ListNode(1)
p1 = ListNode(2)
p2 = ListNode(3)
p3 = ListNode(4)

head.next = p1
p1.next = p2
p2.next = p3
p = non_recurse(head)
while p:
	print(p.val)
	p = p.next

  • 遞歸方式
    class ListNode:
    	def __init__(self, x):
    		self.val = x
    		self.next = None
    
    
    def recurse(head, new_head):
    	if head is None:
    		return
    	if head.next is None:
    		new_head = head
    	else:
    		new_head = recurse(head.next, new_head)
    		head.next.next = head
    		head.next = None
    	return new_head
    
    
    
    head = ListNode(1)
    p1 = ListNode(2)
    p2 = ListNode(3)
    p3 = ListNode(4)
    
    head.next = p1
    p1.next = p2
    p2.next = p3
    new_head = None
    
    p = recurse(head, new_head)
    while p:
    	print(p.val)
    	p = p.next
    	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章