2017-04-07 56 views
-1
public void reverse(int index) { 
    if (first == null) { 
     return; 
    } 
    int count = 0; 
    Node current = first; 
    Node previous = null; 
    Node next; 

    while (current != null && count < index && index> 0) { 
     next = current.next; 
     current.next = previous; 
     previous = current; 
     current = next; 
     count++; 
    } 
    first = previous; 
} 

這是我的代碼。所以我想顛倒一個鏈表並停止索引處的逆向過程。例如,假設我有{One Two Three Four Five},索引是3.所以輸出結果是{Three Two One Four Five}。但對於我的代碼,我能夠在給定索引之前將數據反轉,但由於某種原因,輸出變爲{Three Two One}。如何在給定索引處反轉時保留其餘數據?如何在指定索引處反轉鏈接列表?

回答

0

從我的崗位在Issues with reversing objects in a LinkedList

如果傳遞指數比列表中的元素的數量越多,那麼它只是反轉整個列表。 如果您通過0或1,列表將不受影響

public boolean reverseTillIndex(int index) { 
    int count = 0; 
    if (index == 0) { 
     return false; 
    } 
    Node endCountNode = head; 

    while (count++ < index && endCountNode != null) { 
     endCountNode = endCountNode.next; 
    } 
    count = 0; 

    // standard reverse a list code 
    Node current = head; 
    Node h2 = null; 

    while (current != null && count++ < index) { 
     head = current.next; 
     current.next = h2; 
     h2 = current; 
     current = head; 
    } 

    head = h2; 
    while (h2.next != null) { 
     h2 = h2.next; 
    } 
    h2.next = endCountNode; 
    return true; 
}