Title Description: Flips the section m nodes in the linked list to the nth node; note: M,n satisfies 1≤m≤n≤ chain table length
Example: Given the list 1->2->3->4->5->null, M = 2 and n = 4, return 1->4->3->2->5->null
Previously, it has been implemented in the normal, for the entire list of flip (see: Click to open the link ), this adds a bit of difficulty and sets the position of the rollover. But the basic method has not changed. The difficulty is mainly in the "chain" and "link" operation.
Therefore, we may wish to follow the previous "Palindrome list" (see: Click to open the link) solution, the list is broken, and then processed. This is a lazy way to reduce the difficulty of the problem.
Simply put, take a sample example, you can find the starting position of the flip, here is 2, and then according to this position will be broken list: 1->null, 2->3->4->5->null, which formed two linked lists.
Then, take the second linked list to the head node in turn, and put it behind 1:
1.1->2->null, 3->4->5->null
2.1->3->2->null, 4->5->null
。。。
This cycle is done several times, looping 3 times, that is N-m + 1 times
Then merge the current two linked lists. The code can be obtained as follows:
"" "Definition of Listnodeclass ListNode (object): Def __init__ (Self, Val, next=none): Self.val = Val Self. Next = Next "" "Class Solution:" "@param head:the head of linked list @param m:start position @param n:end Position "" "Def Reversebetween (self, head, M, n): dummy = ListNode ( -1) Dummy.next = head pre = Dummy count = 1 # Find the start of the section you want to flip while count! = M:pre = Pre.next Count + = 1 # Gap for the number of cycles gap = n-m + 1 # The second part second = Pre.next # Sets the tail node of the first part, with the intention of the final merge tail = SE Cond Pre.next = None while gap! = 0:cur = Second second = Second.next temp = Pre.next Pre.next = cur Cur.next = temp gap-= 1 # Two-part Merge Tail.next = sec Ond return dummy.next # write your code here
Flip Chain list II