Python implementation code example for single-chain table inversion, single-chain python
You can use cycles or recursion to reverse a single-chain table.
1. Cyclic inversion of a single-chain table
In the cyclic method, pre is used to point to the forward node, and cur points to the current node. You can point cur-> next to pre each time.
Code:
Class ListNode: def _ init _ (self, x): self. val = x; self. next = None; def nonrecurse (head): # The loop method reverses the linked list if head is None or head. next is None: return head; pre = None; cur = head; h = head; while cur: h = cur; tmp = cur. next; cur. next = pre; pre = cur; cur = tmp; return h; head = ListNode (1); # test code p1 = ListNode (2 ); # create a linked list 1-> 2-> 3-> 4-> None; p2 = ListNode (3); p3 = ListNode (4); head. next = p1; p1.next = p2; p2.next = p3; p = nonrecurse (head); # output chain table 4-> 3-> 2-> 1-> None while p: print p. val; p = p. next;
Result:
4
3
2
1
>>>
2. Recursive single-chain table Inversion
Class ListNode: def _ init _ (self, x): self. val = x; self. next = None; def recurse (head, newhead): # recursion, head is the head node of the original linked list, newhead is the head node of the reverse linked list if head is None: return; if head. next is None: newhead = head; else: newhead = recurse (head. next, newhead); head. next. next = head; head. next = None; return newhead; head = ListNode (1); # test code p1 = ListNode (2 ); # create a linked list 1-> 2-> 3-> 4-> None p2 = ListNode (3); p3 = ListNode (4); head. next = p1; p1.next = p2; p2.next = p3; newhead = None; p = recurse (head, newhead ); # output chain table 4-> 3-> 2-> 1-> None while p: print p. val; p = p. next;
The running result is the same as the preceding one.
Summary
The above is all the content of the code example for reversing a single-chain table in python. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!