1. 程式人生 > >leetcode--92反轉連結串列

leetcode--92反轉連結串列

反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。

說明:
1 ≤ m ≤ n ≤ 連結串列長度。

示例:

輸入: 1->2->3->4->5->NULL, m = 2, n = 4
輸出: 1->4->3->2->5->NULL

/**
 * 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 || head.next==null)
            return head;
        if(m!=1){
            ListNode temp=head.next;
            ListNode preFirst=head;//指向翻轉處的前一個節點的值
            //兩個指標移到反轉處
            for(int i=0;i<m-2;i++){
                temp=temp.next;
                preFirst=preFirst.next;
            }
            //從temp處開始反轉連結串列
            //由於temp是反轉後的最後一個節點,記錄temp這個節點
            ListNode last=temp;
            ListNode pre=temp;//在這開始反轉連結串列
            ListNode pNode=temp.next;
            ListNode next=null;
            for(int i=0;i<n-m;i++){
                next=pNode.next;
                pNode.next=pre;
                pre=pNode;
                pNode=next;
            }
            //反轉前面連結起來,後面連結起來pre是反轉後的頭結點
            preFirst.next=pre;
            last.next=pNode;
        }else{
            ListNode pre=head;
            ListNode pNode=head.next;
            ListNode next=null;
            ListNode last=head;//記錄下last節點
            for(int i=0;i<n-m;i++){
                next=pNode.next;
                pNode.next=pre;
                pre=pNode;
                pNode=next;
            }
            last.next=pNode;//反轉後最後一個節點連結上後續的節點
            return pre;//pre是反轉後的頭結點
        }
        return head;
    }
}