# 程序员必须掌握的数据结构 2

## 1. 括号匹配

``````def par_checker(symbol_str):
"""
括号匹配，list包含栈的功能
append是添加，pop是删除
https://docs.python.org/2/tutorial/datastructures.html
14行
:param symbol_str: 符号字符串
:return: 是否
"""
s = list()  # python的list可以实现stack功能
idx = 0
while idx < len(symbol_str):
symbol = symbol_str[idx]
if symbol == '(':
s.append(symbol)
elif symbol == ')':
s.pop()
idx += 1
if not s:
return True
else:
return False

def test_of_par_checker():
print(par_checker('(())'))
print(par_checker('((()'))
print(par_checker('(a)()((()))'))

if __name__ == '__main__':
test_of_par_checker()

## 2. 二进制转换

``````def base_converter(num, base):
"""
将二进制转换为其他进制
:param num: 数字
:param base: 基数
:return: 数字的字符串
"""
digs = '0123456789ABCDEF'  # 支持16位
base_stack = list()

while num > 0:
rem = num % base
base_stack.append(rem)
num //= base  # 递减一直到0

res_str = ''  # 转换为str
while base_stack:
res_str += digs[base_stack.pop()]

return res_str

if __name__ == '__main__':
print(base_converter(25, 2))
print(base_converter(25, 16))

## 3. 烫手的山芋

``````from queue import Queue

def hot_potato(name_list, num):
"""
烫手的山芋，循环去除
:param name_list: 名字列表
:param num: 循环数
:return: 最后剩下的人
"""
q = Queue()

for name in name_list:
q.put(name)

while q.qsize() > 1:
for i in range(num - 1):  # 每次都死一个循环，最后一个死亡
live = q.get()
q.put(live)

return q.get()

def test_of_hot_potato():
name_list = ['Bill', 'David', 'Susan', 'Jane', 'Kent', 'Brad']
num = 3
print(hot_potato(name_list, num))

if __name__ == '__main__':
test_of_hot_potato()

## 4. 回文

``````from collections import deque

def pal_checker(a_str):
"""
回文，双端队列
:param a_str: 输入字符串
:return: 是否回文
"""
q_char = deque()

for ch in a_str:
q_char.append(ch)

equal = True

# while的终止条件长度或者Bool
while len(q_char) > 1:
first = q_char.pop()
last = q_char.popleft()
if first != last:
equal = False
break

return equal

def test_of_pal_checker():
print(pal_checker('lsdkjfskf'))

if __name__ == '__main__':
test_of_pal_checker()

## 5. 链表反转

``````class Node:
def __init__(self, data=None):
self.data = data
self.next_node = None

"""
链表逆序，交换链表
:return: 新的链表的头结点
"""
prev_node = None

return prev_node

def init_list():
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n1.next_node = n2
n2.next_node = n3
n3.next_node = n4
n4.next_node = n5
return n1

def test_of_reverse_list():
print()