2017-04-07 53 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; 
}