python 双向链表实现
class Node(object):
def __init__(self,item):
self.next = None
self.prev = None
self.item = item
双向链表实现
class DoubleLinkList(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head == None
def length(self):
current = self._head
count = 0
while current.next != None:
current = current.next
count += 1
return count
def travel(self):
if self.is_empty():
return
current = self._head
strs = 'item :' + str(current.item)
while current.next != None:
current = current.next
strs += ', item :' + str(current.item)
print(strs)
return strs
链表头部添加
def add(self,item):
node = Node(item)
node.next = self._head
self._head = node
链表尾部添加
def append(self,item):
node = Node(item)
current = self._head
while current.next != None:
current = current.next
current.next = node
node.next = None
插入
def insert(self,index,item):
if self.is_empty() :
self.add(item)
elif index < 1:
self.add(item)
elif index > self.length() - 1 :
self.append(item)
else:
node = Node(item)
preNode = self._head
count = 0
while count < index - 1 :
preNode = preNode.next
count += 1
node.next = preNode.next
preNode.next = node
删除
def remove(self,item):
if self.is_empty():
return
current = self._head
if current.item == item:
self._head = current.next
else:
while current.next != None:
preNode = current
current = current.next
if current.item == item:
preNode.next = current.next
查询结点
def search(self,item):
current = self._head
if current.item == item:
return current
while current.next != None:
current = current.next
if current.item == item:
return current