?
class Node(object): #定义节点结构
def __init__(self, val=None):
self.val = val
self.next = None
class SingleLinkList(object):
def __init__(self, node=None):
self.__head = node # 定义这个链的起始地址
def is_empty(self): #判空
return self.__head is None
def get_length(self): #求长度
count, cur = 0, self.__head
while cur is not None:
count += 1
cur = cur.next
return count
def ergodic(self): #遍历
cur = self.__head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
def find_val(self, x): #查找
cur = self.__head
while cur is not None:
if cur.val == x:
return True
else:
cur = cur.next
return False
def head_insert(self, x): #头插法
node = Node(x)
if self.__head is None:
self.__head = node
return self.__head
else:
node.next = self.__head
self.__head = node
return self.__head
def tail_insert(self, x): #尾插法
node = Node(x)
cur = self.__head
if cur is None:
self.__head = node
return self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
return self.__head
def insert(self, pos, x): #普通插入
node = Node(x)
cur = self.__head
if pos <= 0:
self.head_insert(x)
return self.__head
if pos >= self.get_length():
self.tail_insert(x)
return self.__head
for i in range(pos-1):
cur = cur.next
node.next = cur.next
cur.next = node
return self.__head
def remove(self, x): #按值删除元素
cur = self.__head
while cur.next is not None:
if self.__head.val == x:
self.__head = self.__head.next
return self.__head
if cur.next.val == x:
cur.next = cur.next.next
else:
cur = cur.next
return -1
def removeAllVal(self, x): #LeetCode题目,
#删除链表中所有值为x的节点
cur = self.__head
if cur.val == x:
self.__head = self.__head.next
while cur.next is not None:
if cur.next.val == x:
cur.next = cur.next.next
else:
cur = cur.next
return self.__head
def removeRepeatVal(self): # LeetCode题目
# 删除排序链表中的重复元素,只保留没有重复出现的数字
pass
if __name__ == "__main__":
sll = SingleLinkList()
print('链表sll是否为空', sll.is_empty())
sll.head_insert(200)
print("链表长度为:", sll.get_length())
sll.tail_insert(2)
sll.tail_insert(4)
sll.tail_insert(1)
sll.tail_insert(3)
print('链表sll是否为空', sll.is_empty())
print("链表长度为:",sll.get_length())
print("是否查到元素", sll.find_val(21))
sll.head_insert(39)
sll.ergodic()
print()
sll.insert(3, 100)
sll.insert(-100, 100)
sll.tail_insert(100)
sll.ergodic()
sll.removeAllVal(100)
sll.remove(2)
print()
sll.ergodic()
|