problem
Reverse a linked list from position m to n.
Notice
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Have you met this question in a real interview? Yes
Example
Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.
Analysis
When dealing with linked list, we must pay attention to the fact that the former node of the target node is the one we need to find, otherwise we can not complete the exchange and other operations. In addition, in order to solve the problem of exchanging the head nodes of the linked list, we can get a new head node out, so that we can solve the problem.
To solve this problem, we first need to traverse to find the location of the first node of m and n. Because it is the inversion of the list, whether it is to find the location of m or n first, the idea is the same. In this paper, n is fixed and m is placed in front of n.next in turn.
Code
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /* * @param head: ListNode head is the head of the linked list * @param m: An integer * @param n: An integer * @return: The head of the reversed ListNode */ public ListNode reverseBetween(ListNode head, int m, int n) { // write your code here ListNode node=new ListNode(0); int i=1; node.next=head; head=node; ListNode preM=null; ListNode preN=null; while(head!=null){ if(i==m){ preM=head; } if(i==n){ preN=head; } head=head.next; i++; } ListNode nodeM=preM.next; ListNode nodeN=preN.next; ListNode afterN=nodeN.next; head=nodeM; while(head!=nodeN){ nodeM=head; head=head.next; nodeM.next=afterN; afterN=nodeM; } nodeN.next=afterN; preM.next=nodeN; return node.next; } }