天天看點

單連結清單反轉操作示例分享

下文是筆者編寫的單連結清單反轉操作

package com.java265.algorithm;

/*
 * 單項連結清單的反轉操作
 * */
public class LinkedListReverse {


    static LinkedList head;

    /**
     * 初始化連結清單
     */
    static void initLinkedList() {

        head = new LinkedList(1);
        head.next = new LinkedList(2);
        head.next.next = new LinkedList(3);
        head.next.next.next = new LinkedList(4);
        head.next.next.next.next = new LinkedList(5);

    }

    /*
     * 列印連結清單
     */
    static void printLinkedList() {
        LinkedList cur = head;
        while (cur != null) {
            System.out.println(cur.value);
            cur = cur.next;
        }
    }

    /**
     * 連結清單反轉
     */
    static void LinkedListResver() {
        LinkedList cur = head.next;
        LinkedList t;
        while (cur != null) {
            t = head;
            t.next = (t.next == cur) ? null : t.next; //此處需特别注意,否則會形成一個回路
            head = cur;
            cur = head.next;
            head.next = t;

        }
    }

    public static void main(String[] args) {
        initLinkedList();
        printLinkedList();
        System.out.println("=================");
        // 反轉連結清單
        LinkedListResver();
        printLinkedList();
    }


}

class LinkedList {
    public int value;
    public LinkedList next;

    public LinkedList(int value) {
        this.value = value;
    }
}      

繼續閱讀