python有链表和指针吗_了解如何更改指针和命令链表实现python
我有以下鏈接列表實現,現在我已經完美地工作了。然而,我并沒有理解,為了教學的目的,我可以證明一個鏈表中包含“下一個指針”的節點。
我的理解是元素按照它們的順序存儲,所以在這種情況下,4,2,3,1。我想在內部改變指針,所以根據指針的實際順序是1,2,3,4。開始或頭指針將在4(這是數組中的第4個元素),第4個元素指向2,這是數組中的第二個元素。
有人可以幫我解釋一下,幫助初學者教這個:
為了澄清,我試圖展示的是:
元素以4,2,3,1的順序進來并存儲在節點的'data'組件中。
我們可以使用節點中的'next pointers'重新排序元素,以便實際順序(打印時)為1.2.3.4,并將4指定為起始節點*這是我需要幫助理解的部分以及如何清晰地演示。
這是我的代碼:
class Node:
def __init__(self,data=None):
self.data=data #this is the data attribute
self.next=None #next pointer
class LinkedList:
def __init__(self):
self.head=Node() #used as a placeholder to point to the first element (doesn't contain anything)
#this is not a data node
def append(self,data): #adding new data to the linked list
new_node=Node(data)
cur=self.head #variable to store the node we are currently looking at
#iterate over each node starting with head, and when next node =None, then we are at the end
while cur.next!=None:
cur=cur.next #traverse through the list
#once we know we are at the end, set the next node equal to our new node
cur.next=new_node
def length(self):
cur=self.head
total=0
while cur.next!=None:
total+=1
cur=cur.next
return total
def display(self):
elems=[]
cur_node=self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print(elems)
def get(self,index):
if index>=self.length():
print("ERROR: 'Get' Index out of range!")
return None
cur_idx=0
cur_node=self.head
while True:
cur_node=cur_node.next
if cur_idx==index: return cur_node.data
cur_idx+=1
# Deletes the node at index 'index'.
def erase(self,index):
if index>=self.length():
print ("ERROR: 'Erase' Index out of range!")
return
cur_idx=0
cur_node=self.head
while True:
last_node=cur_node
cur_node=cur_node.next
if cur_idx==index:
last_node.next=cur_node.next
return
cur_idx+=1
linkedlist=LinkedList()
linkedlist.append(4)
linkedlist.append(2)
linkedlist.append(3)
linkedlist.append(1)
linkedlist.display()
linkedlist.erase(2)
linkedlist.display()
總結
以上是生活随笔為你收集整理的python有链表和指针吗_了解如何更改指针和命令链表实现python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈session实现原理(阿里面试题)
- 下一篇: Unity Shader入门精要笔记(四