We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This is the easiest and most efficient way I've found to reverse a doubly linked list in python 3
#!/bin/python3importmathimportosimportrandomimportreimportsysclassDoublyLinkedListNode:def__init__(self,node_data):self.data=node_dataself.next=Noneself.prev=NoneclassDoublyLinkedList:def__init__(self):self.head=Noneself.tail=Nonedefinsert_node(self,node_data):node=DoublyLinkedListNode(node_data)ifnotself.head:self.head=nodeelse:self.tail.next=nodenode.prev=self.tailself.tail=nodedefprint_doubly_linked_list(node,sep,fptr):whilenode:fptr.write(str(node.data))node=node.nextifnode:fptr.write(sep)## Complete the 'reverse' function below.## The function is expected to return an INTEGER_DOUBLY_LINKED_LIST.# The function accepts INTEGER_DOUBLY_LINKED_LIST llist as parameter.### For your reference:## DoublyLinkedListNode:# int data# DoublyLinkedListNode next# DoublyLinkedListNode prev##defreverse(head):# Write your code hereifheadisNone:returnNonecurr=headwhilecurr:curr.prev,curr.next=curr.next,curr.prevhead=currcurr=curr.prevreturnheadif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')t=int(input())fort_itrinrange(t):llist_count=int(input())llist=DoublyLinkedList()for_inrange(llist_count):llist_item=int(input())llist.insert_node(llist_item)llist1=reverse(llist.head)print_doubly_linked_list(llist1,' ',fptr)fptr.write('\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Reverse a doubly linked list
You are viewing a single comment's thread. Return to all comments →
This is the easiest and most efficient way I've found to reverse a doubly linked list in python 3