题目描述:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
中文理解:
给定一个链表和位置m、n,从链表m位置开始到n位置结束反转这部分链表节点,返回反转后的链表。
解题思路:
分为m为1和不为1两种情况,取到第m个位置前一个位置的节点信息,然后在这个节点后面不断插入m节点之后到n位置的节点,最后返回即可。
代码(java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n)return head;
ListNode fast=head,slow=head;
int mcopy=m;
if(m==1){
fast=new ListNode(0);
fast.next=head;
}
else if(m>=2){
while(m>2){
fast=fast.next;
slow=slow.next;
m--;
n--;
}
slow=slow.next;
n--;
}
ListNode next=null;
while(n>1){
next=slow.next;
slow.next=next.next;
next.next=fast.next;
fast.next=next;
n--;
}
return mcopy==1?fast.next:head;
}
}