【LeetCode】Reverse Linked List II
1444 ワード
タイトル
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example: Given
return
Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
に答える
チェーンテーブルmからnを反転する部分は、2つのステップに分けられ、第1のステップはmノードの位置を見つけることであり、第2のステップはnノードまで反転することである.反転する方法は、1つのノードを読むたびに、それをmノードの前の位置に挿入し、mノードは次のようにします.
---EOF---
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.
に答える
チェーンテーブルmからnを反転する部分は、2つのステップに分けられ、第1のステップはmノードの位置を見つけることであり、第2のステップはnノードまで反転することである.反転する方法は、1つのノードを読むたびに、それをmノードの前の位置に挿入し、mノードは次のようにします.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
/*if(head==null){
return null;
}*/
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode preNode=dummy;
int i=1;
while(preNode.next!=null&&i<m){
preNode=preNode.next;
i++;
}
/*if(i<m){
return head;
}*/
ListNode mNode=preNode.next;
ListNode cur=mNode.next;
while(cur!=null&&i<n){
ListNode next=cur.next;
cur.next=preNode.next;
preNode.next=cur;
mNode.next=next;
cur=next;
i++;
}
return dummy.next;
}
}
---EOF---