day03 顺序链和数组链的代码
2019-04-24 本文已影响0人
LittleBear_6c91
class Node(object):
def init(self, data):
self.data = data
self.next = None
def set_data(self, data):
self.data = data
def set_next(self, node):
self.next = node
def __repr__(self):
return self.data
class NotInListErr(Exception):
def init(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class LinkedList(object):
def init(self):
self.head = None
def append_item(self, item):
i = Node(item)
if self.head is None:
self.head = i
else:
t = self.head
while t.next is not None:
t = t.next
t.set_next(i)
def remove_item(self, item):
if self.head is None:
raise NotInListErr("链表为空")
h = self.head
if item == h.data:
self.head = self.head.next
else:
while h.next is not None and h.next.data != item:
h = h.next
if h.next is None:
raise NotInListErr('该元素不在链表中')
h.set_next(h.next.next)
def remove_by_index(self, index):
if index == 0:
h = self.head
self.head = h.next
else:
left = self.head
h = left.next
for i in range(1, index):
h = h.next
left = left.next
left.next = h.next
def add_item(self, item, index):
data = Node(item)
if index == 0:
data.next = self.head
self.head = data
else:
left = self.head
h = left.next
for i in range(1, index):
if h is not None:
h = h.next
left = left.next
else:
left.next = Node('null')
left = left.next
data.next = h
left.next = data
def size(self):
count = 0
h = self.head
while h is not None:
h = h.next
count += 1
return count
def get_item(self, index):
h = self.head
for i in range(index):
h = h.next
return h.data
def index(self, item):
count = 0
h = self.head
while h is not None and h.data != item:
h = h.next
count += 1
if h is None:
return -1
return count
def __str__(self):
if self.head is None:
return "None"
s = str(self.head.data)
h = self.head.next
while h is not None:
s += '->' + h.data
h = h.next
return s
def test():
node1 = Node('apple')
node2 = Node('pear')
node3 = Node('watermelon')
node4 = Node('Strawberry')
node1.set_next(node2)
node2.set_next(node3)
node3.set_next(node4)
node = node1
while True:
print(node.data)
if node.next:
node = node.next
continue
break
head = node1
while (True):
print(head.data)
if head.next is None:
break
head = head.next
def main():
link_list = LinkedList()
print(link_list)
# link_list.remove_item('apple')
# print("删除:", link_list)
link_list.append_item('apple')
print(link_list)
link_list.append_item('pear')
print(link_list)
link_list.append_item('Strawberry')
print(link_list)
link_list.append_item('Strawberry')
print(link_list)
link_list.remove_item('Strawberry')
print("删除:", link_list)
link_list.remove_item('apple')
print("删除:", link_list)
node1 = link_list.get_item(1)
print("获取:", node1)
link_list.add_item('banana', 5)
print(link_list)
link_list.add_item('1banana', 3)
print(link_list)
print(link_list.index('33'))
if name == 'main':
main()