Topic
Flips the section m nodes in the linked list to the nth node
Precautions
M,n satisfies 1≤m≤n≤ chain table length
Sample Example
Given the list 1->2->3->4->5->null, M = 2 and n = 4, return 1->4->3->2->5->null
Solving
Just flip a part of it
Update linked list based on node value
Complexity of Time: O(n)
Complexity of space: < Span class= "Mrow" id= "mathjax-span-90" > o ( n )
/** * Definition for ListNode * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public class solution { /** * @param ListNode Head is the head of the linked list * @oaram m and n * @retur N: The head of the reversed ListNode */ PublicListNodeReversebetween(ListNode Head,intMintN) {//Write your code if(head==NULL|| Head.next = =NULL|| m<0|| n<0|| M>=n)returnHeadintLen = GetLength (head); ListNode p = head;if(m>len| | N>len)returnHeadinti = m;; while(m>1){//Find the previous node of the rolloverm--; p = p.next; }//Record the value of the node that needs to be flippedArraylist<integer> val =NewArraylist<integer> (); ListNode q = p; while(I<=n && q!=NULL) {Val.add (q.val); Q = q.next; i++; }//Update the original linked list based on the node value. for(I=val.size ()-1; I >=0; i--) {p.val = Val.get (i); p = p.next; }returnHead } Public int GetLength(ListNode head) {intLen =0; ListNode p = head; while(p!=NULL) {len++; p = p.next; }returnLen }}
It's against the idea of a quiz.
Below to find the rollover position after flipping
Reference links
Public class solution { /** * @param ListNode Head is the head of the linked list * @oaram m and n * @retur N: The head of the reversed ListNode */ PublicListNodeReversebetween(ListNode Head,intMintN) {//Write your code if(M >= N | | head = =NULL) {returnHead } ListNode dummy =NewListNode (0);//Insert head nodeDummy.next = head; head = dummy; for(inti =1; I < m; i++) {//Find a node in front of M node if(Head = =NULL) {return NULL; } head = Head.next; } ListNode Premnode = head;//M front nodeListNode Mnode = Head.next;//M-nodeListNode nnode = Mnode;//N nodeListNode Postnnode = Mnode.next;//N Post-node //N before node is inserted into N-node for(inti = m; I < n; i++) {if(Postnnode = =NULL) {return NULL; } ListNode temp = Postnnode.next;//Next nodePostnnode.next = Nnode; Nnode = Postnnode; Postnnode = temp; } mnode.next = Postnnode;after//m next points to nPremnode.next = Nnode;//M front node straight n returnDummy.next; }}
Flip Chain list II