Topics
Give a list of the links, and then we want to flip the section m nodes in this list to the nth node part.
Sample Example
Given the list 1->2->3->4->5->null, M = 2 and n = 4, return 1->4->3->2->5->null
Code and comments
<span style= "FONT-SIZE:18PX;"
>/** * 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 * @return: The head of the reversed ListNode * */Public ListNode Reversebetween (listnode head, int m , int n) {//write your code if (m>=n| |
Head==null) return head;
A node is introduced before the head node, because the head node may be flipped, which can make the head node//Flip the same as the normal node ListNode before=new listnode (0);
Before.next=head;
Head=before;
for (int i=1;i<m;i++) {if (head==null) {return null;
}//Because a node was introduced before the head node, the head here points to the previous node of M Head=head.next;
}//Current node, which is the node of M position, is not moved, always points to the node where M is located listnode mnode=head.next; ListNode dangqiannode=mnode;//The current node, which will be moved later, the value will change ListNode Next=mnode.next;//the next node of the current node listnode the node mqianmiandenode=head;//m the previous position, never changing the for (int i=m;m<n;m++) {if (next=
=null) return null; ListNode temp=next.next;//records the next node of the next node of the current node next.next=dangqiannode;//changes the direction of the next node linked list of the current node,//N of the next node Ext points to the current node dangqiannode=next;//moves the current node backward next=temp;//moves the next node of the current node back to/* The sample procedure: such as: 2->3- >4 2 is the current node (Dangqianjiedian) 3 is the next node of the current node (next) 4 is the next node of the current node (next.next) Temp=next.next; temp=4 record Next.next Next.next=dangqiannode; 3->2 change the direction of the linked list dangqiannode=next;
dangqiangnode=3; Next=temp;
next=4 */}//Avoid the broken list//start of M before the node points to the current node after rollover mqianmiandenode.next=dangqiannode;
The first M-node, (i.e. the M-node not yet flipped),//points to the next node of the current node (flipped) Mnode.next=next;
/* 1->2->3->4->5->NULL;
M-n after flipping (4->3->2) 1 points to the current node after rollover 1->4 2 points to the next node after the flip 2->5 You have 1->4->3->2->5->null; after completion
*//Return the next node of the node introduced before the head node return before.next; }}</span>