单链表的节点实现
class SingleNode(object):
def __init__(self,elem):
self.elem = elem
self.next = None
单链表的实现
class SingleLinkList(object):
def __init__(self,node = None):
self._head = None
def is_empty(self):
return self._head == None
def length(self):
cur = self._head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
cur = self._head
while cur != None:
print(cur.elem)
cur = cur.next
def add(self,item):
node = SingleNode(item)
node.next = self._head
self._head = node
def append(self,item):
node = SingleNode(item)
cur = self._head
if self.is_empty():
self._head = node
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self,pos,item):
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = SingleNode(item)
pre = self._head
count = 0
while count <= (pos-1):
count += 1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self,item):
cur = self._head
pre = None
while cur != None:
if cur.elem == item:
if cur == self._head:
pre.next = cur.next
break
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def search(self,item):
cur = self._head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
|