"092-reverse Linked List II (Reverse single link List ii)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Given a single-linked list, the elements between the first and the nth are transferred.
Given N and m are legal, use the in-place method to resolve (using constant secondary space)
Thinking of solving problems
First find the first element to reverse the precursor (prev), and then calculate the number of elements to be reversed, the element of the head interpolation method, inserted behind the prev, while keeping the chain table continuously open.
Code Implementation
Linked list Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { PublicListNodeReversebetween(ListNode Head,intMintN) {ListNode root =NewListNode (0); ListNode p = root; Root.next = head; for(inti =1; I < m && P! =NULL; i++) {p = p.next; }if(P! =NULL) {ListNode q = p.next; ListNode R;//If M is negative, it is considered to be exchanged from the first start if(M <1) {m =1; } n = n-m +1;//n is the number of nodes to be swapped //There are two nodes to use the tail interpolation method, the number of tail plug is n-1 for(inti =1; I < n && q.next! =NULL; i++) {//For the node to be tail-insertedR = Q.next;//After the Q node, the tail interpolation operation .Q.next = R.next; R.next = P.next; P.next = R; } head = Root.next; }returnHead }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47310547"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "092-reverse Linked List II (Reverse single link List II)"