反轉鏈表

  AcWing打卡活動

《劍指Offer》打卡活動 

週三第一題   反轉鏈表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 * 
 * 思路
 * 需要三個節點
 * 爲了防止節點斷開,我們需要知道當前遍歷節點的上一個節點和下一個節點
 * 如下例子 三個節點不停移動
 * 
 * 例子
 * node1 node2 node3
 * 將node2的next指向node1,這時,node2和node3是斷開的
 * 所以這時我們需要保存node3後面的節點node4
 * node2 node3 node4
 * 將node3指向node2,這樣不斷重複
 * 
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        
        // 使用此種方法至少要保證有兩個節點
        if(head.next == null) {
            return head;
        }
        // 中心節點指向頭結點的下一個
        ListNode hubNode = head.next;
        ListNode nextNode = null;
        // 左節點指向頭結點
        ListNode preNode = head;
        preNode.next = null;
        while(hubNode != null) {
            // 右節點指向中心節點的下一個節點
            nextNode = hubNode.next;
            // 開始反轉列表
            hubNode.next = preNode;
            if(nextNode == null) {
                break;
            }
            // 三個節點都向後移動一位
            preNode = hubNode;
            hubNode = nextNode;
            nextNode = nextNode.next;
        }


        return hubNode;
    }
}

 

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