线性数据结构
1 链表的实现
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class SingleLinkedList(object):
def __init__(self):
# 头节点
self.node = Node(None)
# 头指针
self.head = self.node
# 链表节点数量
self.size = 0
def is_empty(self):
return True if self.head.next == None else False
def get_size(self):
return self.size
# 头插法
def add_head(self, data):
node = Node(data)
node.next = self.head.next
self.head.next = node
self.size+=1
# 尾插法
def add_tail(self, data):
node = Node(data)
if self.head.next == None:
self.head.next = node
self.size+=1
else:
current_node = self.head
while (current_node.next != None):
current_node = current_node.next
current_node.next = node
self.size+=1
# 指定位置插入元素,position从1开始
def insert_at_position(self,data,position):
if position<1 or position>self.size+1:
raise IndexError('插入位置越界')
if position==1:
self.add_head(data)
elif position==self.size:
self.add_tail(data)
else:
current_node=self.head
for i in range(1,position):
current_node=current_node.next
node=Node(data)
node.next=current_node.next
current_node.next=node
self.size+=1
# 显示所有元素
def show_all_data(self):
current_node = self.head.next
result=""
while (current_node != None):
result+=str(current_node.data)+" "
current_node = current_node.next
print(result)
# 删除第一个元素
def delete_head(self):
if self.size==0:
raise Exception('链表为空,错误操作')
elif self.size==1:
self.head.next=None
self.size-=1
else:
self.head.next=self.head.next.next
self.size-=1
# 删除最后一个元素
def delete_tail(self):
if self.size==0:
raise Exception('链表为空,错误操作')
elif self.size==1:
self.head.next=None
self.size-=1
else:
current_node=self.head
for i in range(1,self.size):
if current_node!=None:
current_node=current_node.next
current_node.next=None
self.size-=1
# 删除指定位置的元素
def delete_at_position(self,position):
if position<1 or position>self.size:
raise IndexError('删除位置越界')
elif position==1:
self.delete_head()
self.size-=1
elif position==self.size:
self.delete_tail()
self.size-=1
else:
current_node=self.head
for i in range(position-1):
if current_node!=None:
current_node=current_node.next
current_node.next=current_node.next.next
self.size-=1
# 按值查找元素,返回第一个查找到的位置
def find_node(self,data):
if self.size==0:
raise Exception('链表为空')
current_node=self.head
index=0
while current_node.next!=None:
current_node=current_node.next
index+=1
if current_node.data==data:
break
return index
2 栈的练习(leetCode 032 最长有效括号)
def func(s):
l = len(s)
stack,start,max = [],0,0
for i in range(l):
if s[i] == '(': # 来的是左括号就不更新start,为左括号索引
stack.append(s[i])
else:
# 无论何时,只要stack为空,都重新开始(可能之前已经更新max,也可能)
if len(stack) == 0:
start = i+1
continue
else:
stack.pop()
if len(stack) == 0:
max = max(max,i-start+1)
else:
max = max[i-stack[-1],max]
return max
3 队列的练习(LeetCode 239 滑动窗口最大值)
def func(nums,k):
ls = []
if nums == []:
return []
for i in range(0,len(nums)-k+1):
value = -1000000
for j in range(i,i+k):
if nums[j] >= value:
value = nums[j]
ls.append(value)
return ls