如何在指定的索引处反转链表?

时间:2017-04-07 23:17:48

标签: java linked-list

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}。如何在给定索引处反转时保留其余数据?

1 个答案:

答案 0 :(得分: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;
}