我刚刚开始研究数据结构和算法,这是我对链表的第一次尝试。谁能提供任何方式检查我创建的链表是否正确?还是下面的代码正确与否?
我试图编写一个函数来计算节点数以证明此链表的功能。
Edit1:我想知道此实现对于链接列表是否正确
Edit2:我试图改善UI并删除自由节点。我还能做些什么来进一步改善它?
class Node:
def __init__(self,d):
self.data=d
self.next=None
self.prev=None
class LinkedList:
def __init__(self,head=None):
self.head=head
self.size=0
def add(self,data):
new_node= Node(data)
new_node.next=self.head
if self.head is not None:
self.head.prev=new_node
self.head=new_node
self.size=self.size+1
def count(self):
return self.size
def count_nodes(self,head):
# assuming that head != None
count = 1
current = head
while current.next is not None:
current = current.next
count += 1
return count
def find(self,head,data):
# assuming that head != None
current = head
while current.next is not None:
if current.data==data:
print("found")
current = current.next
def printnodes(self,head):
# assuming that head != None
current = head
while current.next is not None:
print(current.data)
current = current.next
def delete(self,head,data):
current = head
while current.next is not None:
if current.data==data:
current.next.prev=current.prev
current.prev.next=current.next
current = current.next
def insertion(self,head,data,search):
new_node=Node(data)
current = head
while current.next is not None:
if current.data==search:
new_node.next=current
new_node.prev=current.prev
current.prev.next=new_node
current.prev=new_node
current = current.next
mylist=LinkedList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
mylist.add(4)
mylist.add(5)
mylist.add(6)
mylist.add(7)
mylist.add(8)
mylist.add(9)
mylist.add(10)
mylist.add(11)
mylist.add(12)
mylist.printnodes(mylist.head)
mylist.delete(mylist.head,5)
mylist.printnodes(mylist.head)
mylist.insertion(mylist.head,21,8)
mylist.printnodes(mylist.head)