20201130-栈与链表

经过这短短一个月,真的感受到自己的无知与懦弱,比如没有确定的事情,就敢跟小可爱承诺,自己的不成熟导致了这一两年的倒退,这一个月暂时就不实习了,好好把知识补一补,然后将Python好好学一下,简单会SQL是没有未来的,不管在哪个企业,都是以营利为目的,小可爱这么拼,每天5点多就开始上班,你心里难道一点就不愧疚吗?
你愿意留在北京,就代表你选了最难得路走,还想懒,还想混,还想着好事天上飘下来,这是不可能的,从今天开始,把每天的事情记录一下,不记录完整不准睡觉,醒来吧,不能再装睡了。
-- 今天早上在快手啥也没有干,下午回来,睡也不睡,玩了两三个小时,也没有好好午休,也没有好好看书,几乎没有什么所得,以前是这样,但是以后不能这样了,现在17:53,晚饭也不吃了,这个月一个是把开课吧的所有课程全部学完,一个是把实验楼的课程学习完毕,没有撤退可言。
看到小可爱的容颜,我知道自己这辈子不能辜负人家,不能走我爸的后路。
-- Python3简明教程--Python数据结构
先把数据结构刷了一遍:
栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。
栈的介绍
栈允许进行插入和删除操作的一端称为栈顶(top),另一端为栈底(bottom);栈底固定,而栈顶浮动;栈中元素个数为零时称为空栈。插入一般称为进栈(PUSH),删除则称为退栈(POP)。
由于堆叠数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。栈也称为后进先出表。
https://visualgo.net/zh,Visualgo这个网站,我们可以看到整个数据结构的变化过程。可以通过左下角的按钮调慢演示过程。可能也自己动手 code 实现了过程,那么再在网站上演示一下元素的各种操作过程,会带来一些更直观的印象。

创建一个Stack类

class Stack(object):
def init(self, limit=10):
self.stack = [] # 存放元素
self.limit = limit # 堆栈的容量极限

push 进栈

def push(self, data):
## 判断栈是否溢出
if len(self.stack) >= self.limit:
raise IndexError("超出栈容量极限")
self.stack.append(data)

退栈

def pop(self):
if self.stack:
return self.stack.pop()
else:
raise IndexError("pop from an empty stack")

添加其他函数

def peek(self):
if self.stack:
return self.stack[-1]

def is_empty(self):
return not bool(self.stack)

def size(self):
return len(self.stack)

def banlanced_parentheses(parentheses):
stack = Stack(len(parentheses))
for parenthe in parentheses:
if parenthe == '(':
stack.push(parenthe)
elif parenthe == ")":
if stack.is_empty():
return False
stack.pop()
return stack.is_empty()

if name == "main":
examples = ["(((()))", "(())", "(()))"]
print("Blanced parentheses demonstraction: ")
for example in examples:
print(example + ": " + str(banlanced_parentheses(example)))

链表:链表分为单链表和双链表两种。在接下来的内容里,我们将逐步介绍单链表的具体功能是如何实现的。

  1. 创建 Node 类

链表

class Node:
def init(self, data):
self.data = data
self.next = None

创建Linked—LIst类

class LinkList:
def init(self, head=None): # 链表初始化
self.head = head

添加节点

def append(self, new_element):
### 将头部变量指向临时变量current
current = self.head
## 当头部节点存在时
if self.head:
### 循环链表到最后一个元素
while current.next:
current = current.next
current.next = new_element
# 当头部节点不存在时
else:
self.head = new_element

添加is_empty

def is_empty(self):
"""判断链表是否为空"""
# bool() 函数只返回 True 和 False
return not self.head

添加insert 函数

def insert(self, position, new_element):
"""在链表中指定索引处插入元素"""
if position < 0 or position > self.get_length():
raise IndexError("insert 插入时, key值超出了范围")
temp = self.head
### 将插入元素的next元素指向老的头结点,并将新的元素赋值给头结点
if position == 0:
new_element.next = temp
self.head = new_element
return
i = 0
### 遍历找到索引值为position的结点,在其后面插入结点
while i < position:
pre = temp
temp = temp.next
i += 1
pre.next = new_element
new_element.next = temp

添加remove函数

def remove(self, position):
"""删除指定索引的链表元素"""
if position < 0 or position > self.get_length() - 1:
raise IndexError("删除元素的位置超出范围")

i = 0
temp = self.head
### 遍历找到索引值的position 的结点
while temp != None:
  if position == 0:
    self.head = temp.next
    temp.next = None
    return True
  pre = temp
  temp = temp.next
  i += 1
  if i == position:
    pre.next = temp.next
    temp.next = None
    return 

返回链表的长度

def get_length(self):
"""返回链表的长度"""
temp = self.head
# 计算链表的长度变量
length = 0
while temp != None:
length = length + 1
temp = temp.next
# 返回链表长度
return length

遍历链表

def print_list(self):
print("linked_list:")

temp = self.head
while temp is not None:
  print(temp.data)
  temp = temp.next

将链表反转

def reverse(self):
"""将链表反转"""
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
def initlist(self, data_list):
"""将列表转化为链表"""
### 创建头结点
self.head = Node(data_list[0])
temp = self.head
### 逐个为数据创建结点,建立链表
for i in data_list[1:]:
node = Node(i)
temp.next = node
temp = temp.next

我们要给定两个值,如果这两个值都在单链表的链点中,即交换这两个链点在单链表的位置

1->2->3->4->5

input:1 4 output:4->2->3->1->5

def swapNodes(self, d1, d2):
prevD1 = None
prevD2 = None
if d1 == d2:
return
else:
D1 = self.head
while D1 is not None and D1.data != d1:
prevD1 = D1
D1 = D1.next
D2 = self.head
while D2 is not None and D2.data != d2:
prevD2 = D2
D2 = D2.next
if D1 is None and D2 is None:
return
if prevD1 is not None:
prevD1.next = D2
else:
self.head = D2
if prevD2 is not None:
prevD2.next = D1
else:
self.head = D1
temp = D1.next
D1.next = D2.next
D2.next = temp

原文地址:https://www.cnblogs.com/jly1/p/14066191.html