lintcode 中等题: reverse linked list II 翻转链表II

时间:2023-03-08 20:33:07

题目

翻转链表 II

翻转链表中第m个节点到第n个节点的部分

样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

注意

m,n满足1 ≤ m ≤ n ≤ 链表长度

挑战

在原地一次翻转完成

解题

九章中的程序

/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @oaram m and n
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m , int n) {
// write your code
if( m>=n || head == null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
// 找到旋转链表的第一个节点
for(int i=1;i<m;i++){
if( head ==null)
return null;
head = head.next;
}
// 第m个节点的前一个节点
ListNode premNode = head;
// 第m个节点
ListNode mNode = head.next;
ListNode nNode = mNode;
ListNode postnNode = mNode.next;
for(int i=m;i< n;i++){
if(postnNode == null){
return null;
}
// 旋转
ListNode tmp = postnNode.next;
postnNode.next = nNode;
nNode = postnNode;
postnNode = tmp;
}
mNode.next = postnNode;
premNode.next = nNode;
return dummy.next;
}
}

Java Code