|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #先定义一个节点的类
- class Node():
- #初始化
- def __init__(self,elem):
- self.elem=elem
- self.next=[]#节点对象一开始的数据区是有的但是next不知道该指向谁先设置为空
- node=Node(100)
- #定义单链表的类
- class Singlelinklist():
- def __init__(self,node=None):#链表当中必须得存在一个属性指向第一个节点将链表与节点关联起来,属于类属性,因为在使用链表的时候不是拿类来操作的
- self.__head=node#自己内部的函数去使用,对外不暴露,所以将其私有化
- def is_empty(self):
- return self.__head==None
- def length(self):
- #cur游标用来移动遍历节点;将cur置于头一个头结点
- cur=self.__head=None
- #count用来记录数据
- count=0
- while cur!=None:
- count+=1
- cur=cur.next
- return count
- def travel(self):
- """遍历整个列表"""
- cur=self.__head
- while cur!=None:
- print(cur.elem)
- cur=cur.next
- def add(self,item):
- """链表头部添加元素"""
- pass
- def append(self,item):
- """链表尾部添加元素"""
- node=Node(item)
- if self.is_empty():
- self.__head=node
- else:
- cur=self.__head
- while cur.next!=None:
- cur=cur.next
- cur.next=node
- def insert(self,pos,item):
- """在指定的位置添加元素"""
- pass
- def remove(self,item):
- """删除节点"""
- pass
- def search(self,item):
- """查找节点是否存在"""
- pass
- if __name__=='__main__':
- li=Singlelinklist()
- print(li.is_empty())
- print(li.length())
- li.append(1)
- print(li.is_empty())
- print(li.length())
- li.append(2)
- li.append(3)
- li.append(4)
- li.append(5)
- li.append(6)
- li.travel()
复制代码
这个代码我要实现以上的功能但是出了点问题不知道错在哪里,麻烦帮忙指出来并修改一下
错误有两处:
第6行,节点初始化的时候,self.next应该为None,因为你后面在俩女表中插入介电的时候都是这么用的。
第17行,cur=self.__head=None 后面的这个=None是个什么鬼?删掉
- #先定义一个节点的类
- class Node():
- #初始化
- def __init__(self,elem):
- self.elem=elem
- self.next=None#节点对象一开始的数据区是有的但是next不知道该指向谁先设置为空
- node=Node(100)
- #定义单链表的类
- class Singlelinklist():
- def __init__(self,node=None):#链表当中必须得存在一个属性指向第一个节点将链表与节点关联起来,属于类属性,因为在使用链表的时候不是拿类来操作的
- self.__head=node#自己内部的函数去使用,对外不暴露,所以将其私有化
- def is_empty(self):
- return self.__head==None
- def length(self):
- #cur游标用来移动遍历节点;将cur置于头一个头结点
- cur=self.__head
- #count用来记录数据
- count=0
- while cur!=None:
- count+=1
- cur=cur.next
- return count
- def travel(self):
- """遍历整个列表"""
- cur=self.__head
- while cur!=None:
- print(cur.elem)
- cur=cur.next
- def add(self,item):
- """链表头部添加元素"""
- pass
- def append(self,item):
- """链表尾部添加元素"""
- node=Node(item)
- if self.is_empty():
- self.__head=node
- else:
- cur=self.__head
- while cur.next!=None:
- cur=cur.next
- cur.next=node
- def insert(self,pos,item):
- """在指定的位置添加元素"""
- pass
- def remove(self,item):
- """删除节点"""
- pass
- def search(self,item):
- """查找节点是否存在"""
- pass
- if __name__=='__main__':
- li=Singlelinklist()
- print(li.is_empty())
- print(li.length())
- li.append(1)
- print(li.is_empty())
- print(li.length())
- li.append(2)
- li.append(3)
- li.append(4)
- li.append(5)
- li.append(6)
- li.travel()
复制代码
|
|