简体   繁体   中英

How to reverse each half of a doubly linked list?

I'm trying to reverse each half of a doubly linked list, lets assume the list is even and sorting doesn't matter.

lets say I have this input, the list can have any even number of elements.

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

This is the expected output

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

I found the length of the list, to find the middle position, then I tried using a counter to go through each half,however, I feel lost once I start doing lots of while loops. I know how to reverse the whole list but I am stuck further. Does anyone have any ideas?



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;

}

}

I would express the idea in terms of std::list .

Basically, cut from head and tail one element, create two new lists and then merge them. All operations are 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;   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM