我正在玩this code,其中不包含remove_edge
方法。
我的尝试如下:
def remove_edge(self, src, dest):
new_graph = []
for i in range(self.V):
node = self.graph[i]
while node is not None:
if i == src and node.vertex == dest:
new_graph.append(AdjNode(src))
elif i == dest and node.vertex == src:
new_graph.append(AdjNode(dest))
else:
new_graph.append(node)
node = node.next
self.graph = new_graph
...但是稍后稍后调用has_edge时,它将导致索引错误。我假设添加一个没有next
值的新节点在这里可以工作,但是我需要做一些不同的事情。
这是完整的代码:
class AdjNode:
def __init__(self, data):
self.vertex = data # int
self.next = None # behave like a linked list node
class AdjGraph:
def __init__(self, num_vertices):
self.V = num_vertices
self.graph = [None] * self.V
# Function to print the graph
def print_graph(self):
for i in range(self.V):
print("Adjacency list of vertex {}\n head".format(i), end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")
def add_edge(self, src, dest):
# undirected...
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def has_edge(self, src, dest):
for i in range(self.V):
node = self.graph[i]
while node is not None:
if i == src and node.vertex == dest:
return True
if i == dest and node.vertex == src:
return True
node = node.next
return False
# tests:
graph = AdjGraph(5)
graph.add_edge(0, 1)
graph.add_edge(3, 1)
print(graph.has_edge(1, 3)) # True, as expected
graph.remove_edge(1, 3)
print(graph.has_edge(1, 3)) # expecting False here but I get an error:
File "~\Desktop\pytester.py", line 96, in <module>
print(graph.has_edge(1, 3))
File "~\Desktop\pytester.py", line 64, in has_edge
node = self.graph[i]
IndexError: list index out of range