python实现双项链表
实现append,pop,remove,insert,getitme,setitem,iter能力
class Linked:
class Node:
def __init__(self, node, lastobj=None, nextobj=None):
self.last = lastobj
self.next = nextobj
self.data = node
def __repr__(self):
return f'{self.data}'
def __init__(self, node):
self.head = Linked.Node(node)
self.tail = self.head
self.length = 1
def append(self, node):
lastobj = self.tail
newobj = Linked.Node(node,lastobj)
if not self.length:
self.head = newobj
else:
lastobj.next = newobj
self.tail = newobj
self.length += 1
def pop(self):
ret = self.tail
if self.length == 1:
self.head = None
self.tail = None
self.length -= 1
return ret
try:
self.tail = self.tail.last
self.tail.next = None
self.length -= 1
except:
raise IndexError('pop from empty linkedlist')
return ret
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
def remove(self, node):
for i in self:
if node == i.data:
i.last.next = i.next
i.next.last = i.last
self.length -= 1
return
raise ValueError(f'{node} not in linkedlist')
def __getitem__(self, index):
length = self.length
if not isinstance(index, int):
raise ValueError('the index must be an integer')
elif length == 0:
raise IndexError('linkedlist assignment index out of range')
elif index < -length or length <= index:
raise IndexError('linkedlist index out of range')
elif -length <= index < 0:
index += length
for i,node in enumerate(self):
if index == i:
return node
def insert(self, index, node):
target = self[index]
newobj = Linked.Node(node, target.last, target)
target.last = newobj
try:
newobj.last.next = newobj
except:
self.head = newobj
self.length += 1
def __setitem__(self, index, node):
target = self[index]
newobj = Linked.Node(node, target.last, target.next)
try:
newobj.last.next = newobj
except:
self.head = newobj
try:
newobj.next.last = newobj
except:
self.tail = newobj
def __len__(self):
return self.length
s = Linked(20)
s.append(60)
s.append(100)
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
s.pop()
s.pop()
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
s.pop()
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
s.append('a')
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
s.insert(0,50)
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
s[1] = 'b'
print('head:{} tail:{} len:{}'.format(s.head, s.tail, len(s)))
for i in s:
print(i)
head:20 tail:100 len:3
head:20 tail:20 len:1
head:None tail:None len:0
head:a tail:a len:1
head:50 tail:a len:2
head:50 tail:b len:2
50
b