defremoveNthFromEnd(head:ListNode, n:int)->ListNode: ''' 一次遍历算法 ''' new_head = ListNode(-1) new_head.next = head first = new_head second = new_head for i in range(n+1): first = first.next while first != None: first = first.next second = second.next second.next = second.next.next return new_head.next
向右旋转链表
就是把单链表组成一个循环链表
defrotateRight(head:ListNode, k:int)->ListNode: ''' 针对链表进行旋转 ''' if k == 0: return head if head == None: return head temp = head length = 0 while temp.next != None: length += 1 temp = temp.next length += 1 temp.next = head temp = head for i in range((length - k%length -1)): temp = temp.next new_head = temp.next temp.next = None return new_head
defcreate_table()->list: m,n = [int(i) for i in input().split()] # 自动解包 A = [0for i in range(m)] for i in range(m): A[i] = [int(j) for j in input().split()] return A
邻接矩阵转换为邻接表
defcreate_Adj(A)->list: ''' 邻接矩阵转换为邻接表 ''' G = [VNode() for i in range(len(A))] for i,vex in enumerate(A): # 第i个节点,及其所有的边 for node,j in enumerate(vex): if j != 0: p = ArcNode(node, j) p.next = G[i].next G[i].next = p return G
打印邻接表
defdisp_adj(G): for index,i in enumerate(G): p = i.next print(index, end="") while p != None: print(" {}->".format(p.adjvex), end="") p = p.next print()
深度优先搜索
visited = [0for i in range(4)] defDFS(G, v): ''' 深度优先搜索 ''' visited[v] = 1 print(v, end="") p = G[v].next while p != None: w = p.adjvex if visited[w] == 0: DFS(G,w) p = p.next print()
广度优先搜索
defBFS(G, v): ''' 广度优先搜索 ''' q = Queue() visited = [0for i in range(len(G))] print(v,end="") visited[v] = 1 q.put(v) whilenot q.empty(): w = q.get() p = G[w].next while p!=None: if visited[p.adjvex] == 0: print(p.adjvex, end="") visited[p.adjvex] = 1 q.put(p.adjvex) p = p.next print()
Dijkstar 算法
defDijkstra(A, v): ''' Dijkstar 算法 ''' for i in A: for index,value in enumerate(i): if value == -1: i[index] = sys.maxsize dist = A[v] # 原始v到各个顶点的距离
path = [0for i in range(len(A))] for i in range(len(A)): if A[v][i] != -1: path[i] = v else: path[i] = -1
s = [0for i in range(len(A))] s[v] = 1
for i in range(len(A)): mindis = sys.maxsize # 寻找最小路径长度顶点u for j in range(len(A)): if s[j] == 0and dist[j] < mindis: u = j mindis = dist[j] s[u] = 1 for j in range(len(A)): if s[j] == 0: if A[u][j] < sys.maxsize and dist[j] > 0and dist[u]+A[u][j] < dist[j]: dist[j] = dist[u] + A[u][j] path[j] = u return path, dist