leetcode刷題(92)——指定範圍反轉單鏈表

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

還是反轉鏈表,只不過是要考慮反轉範圍的邊界結點問題。 

時間複雜度O(n),空間複雜度O(1)

/**
 * 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(head==null||m==n){return head;}
        ListNode cur = head;
        ListNode prev = null;
        for(int i=0;i<m-1;i++){
            prev = cur;
            cur = cur.next;
        }
        ListNode con = prev;
        ListNode tail = cur;
        prev = cur;
        cur = cur.next;
        for(int i=m;i<n;i++){
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        if(m==1){
            head = prev;
        }else{
            con.next = prev;
        }
        tail.next = cur;
        return head;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章