溫馨提示×

java怎么實現單鏈表的反轉

小億
60
2023-12-06 19:21:05
欄目: 編程語言

要實現單鏈表的反轉,可以按照以下步驟進行:

  1. 創建一個新的鏈表,作為反轉后的鏈表。
  2. 遍歷原鏈表,將每個節點插入到新鏈表的頭部。
  3. 返回新鏈表作為反轉后的鏈表。

以下是用Java實現單鏈表反轉的示例代碼:

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class LinkedListReverse {
    public static ListNode reverse(ListNode head) {
        ListNode newHead = null;
        while (head != null) {
            ListNode nextNode = head.next;
            head.next = newHead;
            newHead = head;
            head = nextNode;
        }
        return newHead;
    }

    public static void main(String[] args) {
        // 創建一個示例鏈表 1->2->3->4->5
        ListNode head = new ListNode(1);
        ListNode second = new ListNode(2);
        ListNode third = new ListNode(3);
        ListNode fourth = new ListNode(4);
        ListNode fifth = new ListNode(5);

        head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;

        // 反轉鏈表
        ListNode newHead = reverse(head);

        // 打印反轉后的鏈表值
        ListNode currentNode = newHead;
        while (currentNode != null) {
            System.out.print(currentNode.val + " ");
            currentNode = currentNode.next;
        }
        // 輸出結果: 5 4 3 2 1
    }
}

在上述示例代碼中,我們創建了一個單鏈表,并使用 reverse 方法將其反轉。最后,我們遍歷反轉后的鏈表,并打印每個節點的值。輸出結果為 5 4 3 2 1,表示鏈表已成功反轉。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女