LinkedList
and Node
classes¶class LinkedList:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __init__(self):
self.head = None
self.count = 0
def prepend(self, value):
self.head = LinkedList.Node(value, self.head)
self.count += 1
def __len__(self):
return self.count
def __iter__(self):
n = self.head
while n:
yield n.val
n = n.next
def __repr__(self):
return '[' + ', '.join(str(x) for x in self) + ']'
lst = LinkedList()
for i in range(10):
lst.prepend(i)
lst
append
¶class LinkedList (LinkedList):
def append(self, value):
if len(self) == 0:
self.prepend(value)
else:
n = self.head
while n.next:
n = n.next
n.next = LinkedList.Node(value)
self.count += 1
lst = LinkedList()
for i in range(10):
lst.append(i)
lst
class LinkedList (LinkedList):
def __init__(self):
self.head = self.tail = None
self.count = 0
def prepend(self, value):
self.head = LinkedList.Node(value, self.head)
if not self.tail:
self.tail = self.head
self.count += 1
def append(self, value):
if len(self) == 0:
self.prepend(value)
else:
self.tail.next = LinkedList.Node(value)
self.tail = self.tail.next
self.count += 1
lst = LinkedList()
for i in range(10):
lst.append(i)
lst
class LinkedList (LinkedList):
def del_head(self):
assert(len(self) > 0)
if self.head:
self.head = self.head.next
self.count -= 1
if len(self) == 0:
self.tail = None
lst = LinkedList()
for i in range(10):
lst.append(i)
lst.del_head()
lst.del_head()
lst
class LinkedList (LinkedList):
def del_tail(self):
assert(len(self) > 0)
# YUCK!!!
if len(self) == 1:
self.head = self.tail = None
else:
n = self.head
while n.next is not self.tail:
n = n.next
n.next = None
self.tail = n
self.count -= 1
lst = LinkedList()
for i in range(10):
lst.append(i)
lst.del_tail()
lst.del_tail()
lst
class LinkedList:
class Node:
def __init__(self, val, prior=None, next=None):
self.val = val
self.prior = prior
self.next = next
def __init__(self):
self.head = LinkedList.Node(None) # *sentinel* node!
self.head.prior = self.head.next = self.head
self.count = 0
def prepend(self, value):
n = LinkedList.Node(value, prior=self.head, next=self.head.next)
# important: Python carries out multiple assignments from *left to right*!
self.head.next.prior = self.head.next = n
self.count += 1
def append(self, value):
n = LinkedList.Node(value, prior=self.head.prior, next=self.head)
n.prior.next = n.next.prior = n
self.count += 1
def del_head(self):
assert(len(self) > 0)
to_del = self.head.next
# note: following is location agnostic!
to_del.prior.next = to_del.next
to_del.next.prior = to_del.prior
self.count -= 1
def __len__(self):
return self.count
def __iter__(self):
n = self.head.next
while n is not self.head:
yield n.val
n = n.next
def __repr__(self):
return '[' + ', '.join(str(x) for x in self) + ']'
lst = LinkedList()
for i in range(10):
lst.prepend(i)
for i in range(10):
lst.append(i)
lst.del_head()
lst
Run-time complexities for circular, doubly-linked list of $N$ elements: