簡體   English   中英

Java中的反向LinkedList問題

[英]Reverse LinkedList issue in Java

反向鏈接列表的后半部分

假設我們有1-2-3-4

輸出:1-2-4-3

假設我們有1-2-3-4-5

輸出:1-2-3-5-4 //但是我希望輸出在奇數條件下為1-2-5-4-3,如何修改下面的代碼?

public static ListNode reverseSecondHalfList(ListNode head) {
    if (head == null || head.next == null)      return head;
    ListNode fast = head;
    ListNode slow = head;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    ListNode pre = slow.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = slow.next;
        slow.next = cur;
        cur = pre.next;
    }
    return head;
}

我的方法:首先找到要交換的起始位置,然后每次交換“ pre”節點和“ cur”,直到cur.next!= null

嘗試這個

    public static ListNode reverseSecondHalfList(ListNode head) {
    if (head == null || head.next == null)      return head;

    // Add one more node before head, it will help us find the node which before mid note.
    ListNode newHead  = new ListNode(0);
    newHead.next= head;
    ListNode fast = newHead;
    ListNode slow = newHead;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    ListNode pre = slow.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = slow.next;
        slow.next = cur;
        cur = pre.next;
    }
    return head;
}

我從一種方法中提取了一些代碼,使代碼更清潔

  public static ListNode reverseSecondHalfList2(ListNode head) {
    if (head == null || head.next == null)      return head;

    ListNode preMid = getPreMidListNode(head);
    reverse(preMid);
    return head;
}

private static void reverse(ListNode preMid) {
    ListNode pre = preMid.next;
    ListNode cur = pre.next;
    while (cur != null) {
        pre.next = cur.next;
        cur.next = preMid.next;
        preMid.next = cur;
        cur = pre.next;
    }
}

private static ListNode getPreMidListNode(ListNode head) {
    // Add one more node before head, it will help us find the node which before mid note.
    ListNode newHead  = new ListNode(0);
    newHead.next= head;
    ListNode fast = newHead;
    ListNode slow = newHead;
    while (fast.next != null && fast.next.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    return slow;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM