Topic:
Reverse a linked list from position m to N. Do it in-place and in One-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
Return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.
test instructions and analysis: reverses the node of the linked list from M to N, where 1≤m≤n≤length of list. The main thing is to use a prenode to record the current point before a point and nextnode record the current point after a point, so that the current point of the next pointer to Prenode, and then Prenode = node, node = NextNode, continue to swap the back point. Note The m==1, which is a little different when flipping from the first point onwards.
Code:
/*** Definition for singly-linked list. * public class ListNode {* int val, * ListNode next; * ListNode (in T x) {val = x;}}*/classSolution { PublicListNode Reversebetween (ListNode head,intMintN) {if(m==n)returnHead; ListNode Startnode= head;//record the point of M-1ListNode Prenode = head;//record the previous point of the current pointListNode nextnode = head;//record the next point of the current pointListNode node =Head; intindex = 1; if(m==1) {//The first point starts flipping while(Index <=N) {//node = node.next;NextNode = Node.next;//record the next point if(Index!=1) {//The exchange of pointers is not the first pointNode.next =Prenode; Prenode=node; } node=NextNode; Index++; } Startnode.next=node; returnPrenode; }Else{//back point start flippingListNode temp =NULL; while(Index <=N) { if(index = = m-1) {//record rollover point before a pointStartnode =node; Temp=Node.next; } nextnode= Node.next;//record the next point if(Index!=1 && index > m) {//The exchange of pointers is not the first pointNode.next =Prenode; } Prenode=node; Node=NextNode; Index++; } Startnode.next=Prenode; Temp.next=node; returnHead; } }}
[Leetcode] 92. Reverse Linked List II Java