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 the list.
Idea: According to test instructions, you need to reverse the node between a given number
Specifically, add a pseudo-head node to the original list (the benefits of this: the original node of the list can be treated as a normal node, convenient to operate), and get the beginning and end nodes of the reverse node (for ease of operation, the first node that starts the reversal node and the last node of the final reversal node, That is, the middle part is the node that needs to be reversed, and then reverses the middle node to get the final sequence.
The specific implementation is as follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {val = x;} *} * / Public class solution { PublicListNodeReversebetween(ListNode Head,intMintN) {if(Head = =NULL){return NULL; }if(M = = N) {returnHead }intFlag =0; ListNode P1 = head;//used to point to the previous node that started the reverse nodeListNode P2 = head;///used to point to the last node of the reverse node P1---the node between P2 is the node to invert (not including P1 p2)ListNode Phead =NewListNode (0); Phead.next = head; ListNode p = phead; while(P! =NULL) {flag++;if(flag = = m) {p1 = p;//point to the previous node of the start Reversal node}if(Flag = = n+1) {P2 = P.next;//point to the last node of the end reversal node Break; } p = P.next; } ListNode pp1 = P1.next; ListNode pp2 = Pp1.next; ListNode pp3 = Pp2.next; Pp1.next = p2; while(pp3! = p2) {pp2.next = PP1; PP1 = PP2; PP2 = PP3; PP3 = Pp3.next; } pp2.next = PP1; P1.next = PP2;returnPhead.next; }}
Leetcode 92. Reverse Linked List II