如何反转双向链表的每一半?

How to reverse each half of a doubly linked list?

我正在尝试反转双向链表的每一半,让我们假设该列表是偶数并且排序无关紧要。

假设我有这个输入, 该列表可以包含任意偶数个元素。

1 <=> 5 <=> 8 <=> 3 <=> 2 <=> 10

这是预期的输出

8 <=> 5 <=> 1 <=> 10 <=> 2 <=> 3

我找到了列表的长度,找到了中间的位置,然后我尝试使用计数器遍历每一半,但是,一旦我开始做很多 while 循环,我就会感到迷茫。我知道如何反转整个列表,但我被困得更深了。 有人有什么想法吗?



template <class T>
void DoubyLinkedList<T>:: ReverseFunction() {

node<T> *ptr = head;

//find length of list

int length = 0;
while (ptr!=NULL) {
ptr = ptr->next;
length++;
}

ptr = head;

int c = 1;
//This code reverses the whole list 
while (ptr != NULL ) {

    node<T> *tmp = ptr->next;

    ptr->next = ptr->prev;

    ptr->prev = tmp;
}

    if (tmp == NULL) {

        tail = head;
        head = ptr;

    }
    ptr = tmp;

}

}

我会用 std::list 来表达这个想法。

基本上,从头部和尾部切割一个元素,创建两个新列表,然后合并它们。所有操作都是 O(1).

std::list<int> reverseHalfs(std::list<int> &l) {
    assert((l.size() % 2) == 0);
    std::list<int> newHead;
    std::list<int> newTail;
    while (l.size() > 1) {
        newHead.push_front(l.front());
        newTail.push_back(l.back());
        l.pop_front();
        l.pop_back();
    }
    newHead.splice(end(newHead), newTail);
    return newHead;   
}