前言
- 文章来源:CSDN@LawsonAbs
- 使用python定义一个单链表
class Node:
def __init__(self,data):
self.data = data
self.next = None;
return
def has_value(self,value):
if self.data == value:
return True
else:
return False
class singlelink():
def __init__(self):
self.head = None
self.tail = None
self.length = 0
return
def isempty(self):
return self.length == 0
def add_node(self,item):
if not isinstance(item,Node):
item = Node(item)
if self.head is None:
self.head = item
self.tail = item;
else:
self.tail.next = item
self.tail = item
self.length += 1
return
def insert_node(self,index,data):
if self.isempty():
print("this link is empty")
return
if index < 0 or index >= self.length:
print("error:out of index")
return
item = Node(data)
if index == 0:
item.next = self.head
self.head = item
self.length += 1
return
j = 0
node = self.head
prev = self.head
while node.next and j < index:
prev = node
node = node.next
j+=1
if j==index:
item._next = node
prev._next = item
self.length += 1
def print_link(self):
current_node = self.head
while current_node is not None:
print(current_node.data,end=' ')
current_node = current_node.next
return
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
link = singlelink()
for node in [n1,n2,n3,n4]:
link.add_node(node)
link.print_link()
|