[Data Structure] Linked List Implementation in Python

时间:2021-02-26 06:04:58
class Empty(Exception):
pass class Linklist: class _Node:
# Nonpublic class for storing a linked node
__slots__='_element','_next' def __init__(self,ele,ne):
self._element=ele
self._next=ne def __init__(self):
self._head=None
self._size=0
self._tail=None def __len__(self):
return self._size def is_empty(self):
return self._size==0 def add_first(self,e):
self._head=self._Node(e,self._head)
if self._size==0:
self._tail=self._head
self._size+=1 def add_last(self,e):
newlastnode=self._Node(e,None)
if ~self.is_empty():
self._tail._next=newlastnode
self._tail=newlastnode
else:
self._tail=newlastnode
self._size+=1 def remove_first(self):
if self.is_empty():
raise Empty("The linked is empty")
self._head=self._head._next
self._size-=1