Skip to content

Instantly share code, notes, and snippets.

@girish3
Created October 24, 2016 03:06
Show Gist options
  • Save girish3/0182659a3bd2cf73aba9db273383c06b to your computer and use it in GitHub Desktop.
Save girish3/0182659a3bd2cf73aba9db273383c06b to your computer and use it in GitHub Desktop.
class DoubleList(object):
head = None
tail = None
size = 0
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = self.tail = new_node
self.size = 1
else:
new_node.prev = self.tail
new_node.next = None
self.tail.next = new_node
self.tail = new_node
self.size += 1
def append_by_node(self, new_node):
if self.head is None:
self.head = self.tail = new_node
self.size = 1
else:
new_node.prev = self.tail
new_node.next = None
self.tail.next = new_node
self.tail = new_node
self.size += 1
def remove_by_value(self, node_value):
current_node = self.head
while current_node is not None:
if current_node.data == node_value:
# if it's not the first element
if current_node.prev is not None:
current_node.prev.next = current_node.next
current_node.next.prev = current_node.prev
else:
# otherwise we have no prev (it's None), head is the next one, and prev becomes None
self.head = current_node.next
current_node.next.prev = None
self.size -= 1
current_node = current_node.next
# assuming that node is present
def remove_by_node(self, node):
if self.size == 1:
self.head = None
self.tail = None
return
prev = node.prev
next = node.next
if prev is not None:
prev.next = next
if next is not None:
next.prev = prev
def remove_tail(self):
if self.size == 0:
return
prev = self.tail.prev
self.size -= 1
if prev is not None:
prev.next = None
self.tail = prev
else:
self.head = None
self.tail = None
def remove_head(self):
if self.size == 0:
return
next = self.head.next
self.size -= 1
if next is not None:
next.prev = None
self.head = next
else:
self.head = None
self.tail = None
def get_size(self):
return self.size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment