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实现原理(阿里面试题)
- 下一篇: python3 链表_Python3链表