[LeetCode] 92. Reverse Linked List II Java

來源:互聯網
上載者:User

標籤:style   val   ace   span   題目   ebe   代碼   java   condition   

題目:

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的節點,其中1 ≤ m ≤ n ≤ length of list。主要是要用一個preNode記錄當前點前一個點和nextNode記錄當前點後一個點,這樣就可以將當前點的next指標指向preNode,然後將preNode = node, node = nextNode,繼續交換後面的點即可。注意的是m==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(m==n) return head;        ListNode startNode = head; //記錄m-1的點        ListNode preNode = head;        //記錄當前點的前一個點        ListNode nextNode = head; //記錄當前點的下一個點        ListNode node = head;        int index = 1;        if(m==1){       //第一個點開始翻轉            while(index <= n){//                node = node.next;                nextNode = node.next;       //記錄下一個點                if(index !=1){      //不是第一個點就交換指標                    node.next = preNode;                    preNode = node;                }                node = nextNode;                index++;            }            startNode.next = node;            return preNode;        }else{      //後面點開始翻轉            ListNode temp = null;            while(index <=n){                if(index == m-1) {      //記錄翻轉點前一個點                    startNode = node;                    temp = node.next;                }                nextNode = node.next;       //記錄下一個點                if(index !=1 && index > m){      //不是第一個點就交換指標                    node.next = preNode;                }                preNode = node;                node = nextNode;                index++;            }            startNode.next = preNode;            temp.next = node;            return head;        }    }}

 

[LeetCode] 92. Reverse Linked List II Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.