2016-03-19 12 views
0

umge zweite Hälfte der verlinkten ListeReverse-LinkedList Problem in Java

Angenommen, wir haben 1-2-3-4

Ausgang: 1-2-4-3

Angenommen, wir haben 1- 2-3-4-5

Ausgabe: 1-2-3-5-4 // aber ich möchte, dass die Ausgabe 1-2-5-4-3 in der ungeraden Bedingung ist, wie der Code geändert wird unten?

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; 
} 

Meine Methode: Zum einen die Startposition finden tauschen "pre" getauscht werden, dann Knoten und "Aktuell" jedes Mal, bis cur.next = null

+0

ich sehe nichts in dem Code, der versteht, wo es in der Liste ist. Sicher müssen Sie zählen, während Sie durch die Liste vorrücken? –

+0

Weil es nur die Hälfte umkehren muss, also verwende ich nicht den Counter @MartinBroadhurst – KKKK

Antwort

1

Versuchen Sie, diese

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; 
} 
!

Und ich extrahieren einige Code von einer Methode Make-Code Reiniger

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; 
} 
+0

Das ist genau was ich will! – KKKK