简体   繁体   中英

Is it possible to reverse a doubly circular linked list? if Yes, then how?

I am a bit confused, as one of my friend said it not possible. As it's totally symmetric.

I have googled a bit but I am still confused

Yes; simply swap the previous and next pointers, as well as any head and tail pointers. Can you explain how your friend claims that the list is symmetric?

It is not impossible, it might require some extra care to design the algorithm, but that is with most (all) algorithms where you have to iterate and modify the data structure.

You can simply swap the head and tail , and then iterate over your linked list and swap the next and previous references for each node. You furthermore need to make sure you stop doing that after one full iteration.

A sample algorithm in Python would look like:

class CircularDoubleLinkedList:

    # ...

    def reverse(self):
        
        start = cur = self.head
        if cur is not None:
            
            cur = cur.previous
        while cur is not None and cur is not start:
            
            cur = cur.previous  # move to the next node

For each node N of the list, you just need to swap N.next and N.prev . After this, you change the reference of head to be the new head.next . If there is a tail , it should be updated to tail.prev .

Just for better visualization:

在此处输入图片说明

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