Title: Reverse list of nodes from m-n locations
For example:
Given1->2->3->4->5->null, m = 2 and n = 4,
Return1->4->3->2->5->null.
The nodes from the second to the fourth are reversed.
where m and n satisfy the condition:
1≤ m ≤ N ≤length of the list.
Ideas:
Still in reverse order, consider using a secondary space stack.
The nodes of the m-n are sequentially placed into the stack and marked with the front and back two nodes adjacent to the stack node Pfirst and Psecond.
(if m==1,pfirst=null, regardless of whether n is the length of the list, there is no effect on the psecond situation.) )
The code is as follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} */import java.util.*;p Ublic class Solution {public ListNode Reversebetween (listnode head, int m, int n) { if (head==null) return null; if (m==n) return head; stack<listnode> stack=new Stack (); The nodes of the m-n are put into the stack, and the two nodes adjacent to each other are marked; int num=1; ListNode Pfirst=null; ListNode Psecond=null; ListNode P=head; Special cases, when m==1, the head node changes; if (m==1) {pfirst=null; } for (; num<=n;num++) {//record pfirst; if (num<m) {if (num==m-1) {pfirst=p; } P=p.next; } else if (NUM>=M&AMp;&num<=n) {Stack.push (P); P=p.next; }}//The general condition of recording Psecond,psecond still applies to the special case of n=length of list; Psecond=p; Start the operation of the linked list; if (pfirst==null) {head=stack.pop (); Pfirst=head; } while (!stack.empty ()) {Pfirst.next=stack.pop (); Pfirst=pfirst.next; } Pfirst.next=psecond; return head; }}
Linked List--flips the node position of a single linked list from M to n