[英]Why are the nodes in my linked list graph going in reverse numerical order?
我正在嘗試使用鏈表操作創建一個鄰接列表,並且我的圖形邊緣顯示相反的數字順序而不是順序。 例如,我的 output 是 Node 0: 3 2 1 而不是 Node 0: 1 2 3
class Node:
def __init__(self, value):
self.vertex = value
self.next = None
class AdjGraph:
def __init__(self, data):
self.data = data
self.graph = [None] * self.data
# Add edges
def addEdge(self, vertice, edge):
node = Node(edge)
node.next = self.graph[vertice]
self.graph[vertice] = node
# Print the graph
def printGraph(self):
adj_list = "Adjacency List"
for i in range(self.data):
adj_list += "\n\nNode " + str(i) + ": "
temp = self.graph[i]
while temp:
adj_list += str(temp.vertex) + " "
temp = temp.next
return adj_list
您需要對 addEdge function 進行一些小改動。 您當前的 function 基本上抓取現有節點並將其附加到新節點,即與我們正在尋找的完全相反。
在查看解決方案之前,先看看您的代碼做了什么。 讓我們插入 0。
## graph[0] = None (since there are no nodes)
node = Node(edge) # Node { vertex: 0 }
node.next = self.graph[vertice] ## Node {vertex:0, next: None} since graph[0] is null right now
self.graph[vertice] = node ## graph[0] = Node {vertex: 0, next: None}
現在讓我們插入 1 -
node = Node(edge) ## Node { vertex: 1 }
node.next = self.graph[vertice] ## Node { vertex: 1, next: { vertex: 0, next: None} }
## Remember what we got in the previous insertion, graph[0] has the first node
## i.e -> 0
self.graph[vertice] = node
因此,在每次插入時,您都會首先獲得最新的元素,因此您的結果與您正在尋找的完全相反。
這是我對此的解決方案(可能並不完美) -
class AdjGraph:
def addEdge(self, vertice, edge):
currNode = self.graph[vertice] # The existing node at specified index
newNode = Node(edge) # Creating a new node
if currNode == None: # If there are no elements in this node
self.graph[vertice] = newNode
return
while currNode != None: # Traversing
if currNode.next == None:
currNode.next = newNode # Attaching the New Node to the tail of the existing node
break
currNode = currNode.next
ag = AdjGraph(1)
ag.addEdge(0,0)
ag.addEdge(0,1)
ag.addEdge(0,2)
ag.addEdge(0,3)
print(ag.printGraph())
## Result
## Adjacency List
## Node 0: 0 1 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.