employer cover photo
employer logo

Pregunta de entrevista de VMware

Reverse Linked list in Python

Respuesta de la entrevista

Anónimo

23 de ene de 2017

class node: def __init__(self): self.data = None # contains the data self.next = None # contains the reference to the next node class linked_list: def __init__(self): self.cur_node = None def add_node(self, data): new_node = node() # create a new node new_node.data = data new_node.next = self.cur_node # link the new node to the 'previous' node. self.cur_node = new_node # set the current node to the new one. def list_print(self): node = self.cur_node # cant point to ll! while node: print node.data node = node.next def rev_list(self): node = self.cur_node c = [] while node: c.append(node.data) node =node.next while len(c) > 0: print c[-1] del c[-1] ll = linked_list() l2 = linked_list() ll.add_node(1) ll.add_node(2) ll.add_node(3) ll.add_node(4) ll.list_print() print "Reverse List:" ll.rev_list()