反轉一個單連結串列。

Richal發表於2018-09-04
public class reverseList {
    public static void main(String[] args) {
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode three = new ListNode(3);
        ListNode four = new ListNode(4);
        ListNode five = new ListNode(5);
        one.next = two;
        two.next = three;
        three.next = four;
        four.next = five;
        five.next = null;
        printLink(one);
        ListNode head = reverseList(one);
        printLink(head);
    }

    public static void printLink(ListNode head) {
        if (null == head) System.out.println("head is null");
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }

    }

    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode prev = null;
        while (null != head) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}
複製程式碼


相關文章