# reverse a doubly circular linked list by swapping node value in python

Python program for reverse a doubly circular linked list by swapping node value. Here problem description and explanation.

``````#  Python 3 Program
#  Reverse a doubly circular linked list by swapping value

#  Linked list node
class LinkNode :
def __init__(self, data, back, next) :
self.data = data
self.back = back
self.next = next

class CircularDoublyLL :
def __init__(self) :
self.front = None
self.tail = None

#  Add new node at the end of linked list
def addNode(self, data) :
node = LinkNode(data, None, None)
#  When new node is successfully created
if (self.front == None) :
#  Add first node of linked list
self.front = node
self.tail = node
else :
#  Add node at last position
self.tail.next = node
node.back = self.tail
self.tail = node

#  Connect the last node in the linked list to front
self.tail.next = self.front
self.front.back = self.tail
#  Set node data
node.data = data

#  Print linked list nodes
def printElement(self) :
if (self.front == None) :
print("\n Empty Linked List ")
else :
temp = self.front
print("\n Linked List from Front to Tail ")
#  Display doubly linked list from start to last node
while (temp != None) :
print("",temp.data, end = " ")
if (temp == self.tail) :
#  When get last node
temp = None
else :
temp = temp.next

temp = self.tail
print("\n Linked List from Tail to Front ")
#  Display doubly linked list from last to start node
while (temp != None) :
print("",temp.data, end = " ")
if (temp == self.front) :
#  When get first node
temp = None
else :
temp = temp.back

#  Reverses the elements of doubly linked list
#  using swap node values
def reverseElement(self) :
#  Get first node
first = self.front
#  Get last node
last = self.tail
temp = 0
#  Reverse operation
while (first != None and last != None) :
if (first != last) :
#  Swap the node value
temp = first.data
first.data = last.data
last.data = temp
if (first.next == last) :
#  Stop reverse operation, or use break
first = None
last = None
else :
first = first.next
last = last.back

else :
#  Stop reverse operation, or use break
first = None
last = None

def main() :
cll = CircularDoublyLL()
#  Add linked list node
cll.addNode(1)
cll.addNode(2)
cll.addNode(3)
cll.addNode(4)
cll.addNode(5)
cll.addNode(6)
print("\n Before reverse linked list", end = "")
cll.printElement()
cll.reverseElement()
print("\n\n After reverse linked list", end = "")
cll.printElement()

if __name__ == "__main__": main()``````

Output

`````` Before reverse linked list
Linked List from Front to Tail
1  2  3  4  5  6
Linked List from Tail to Front
6  5  4  3  2  1

After reverse linked list
Linked List from Front to Tail
6  5  4  3  2  1
Linked List from Tail to Front
1  2  3  4  5  6``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.