简单尝试实现一个单向链表结构,以及插入删除,查找元素,切片等方法的实现。包括(append,insert,pop,remove,search,index,slice)添加这些操作是为了模仿列表List类。
这里采用了两个类,Node节点类,包含节点自身数据和指向下一个节点的指针;LinkedList链表类,包含这个链表的头节点,和链表的长度。
首先是节点类
class Node():
def __init__(self,initdata):
self.data=initdata
self.next=None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data=newdata
def setNext(self,newnext):
self.next=newnext
链表类
以及添加元素操作add。添加元素总是添加在链表的头部,因此需要生成一个新节点,代替旧的链表的头节点LinkedList.head。
class LinkedList:
def __init__(self):
self.head=None
self.count=0
def isEmpty(self):#是否为空
return self.count==0
def add(self,item):#添加一个元素item
temp=Node(item)
temp.setNext(self.head)
self.head=temp
self.count += 1
def length(self):#链表的长度
#current=self.head
#count=0
#while current != None:
#count=count+1
#current= current.getNext()
return self.count
查找元素
查找某个元素是否在链表中,以及它的索引值。(注意定义的这些方法仍在LinkedList类之中,因此代码要缩进)
def search(self,item):#返回布尔值
current=self.head
found=False
while current != None and not found:
if current.getData()==item:
found =True
else:
current=current.getNext()
return found
def index(self,item):#返回索引值,如果不在链表中则没有返回值(None)
current=self.head
count=0
found=False
while current != None and not found:
if current.getData()==item:
found =True
else:
current=current.getNext()
count+=1
if found:#找到才返回
return count
插入元素
append插在尾部,insert插在索引处。
def append(self,item):#在末尾添加元素
current=self.head
previous=None
temp=Node(item)
if current==None:
self.head=temp
#如果在链表类的属性中多加个尾节点,会方便很多
else:
num=1
while num < self.count:
pervious=current
current=current.getNext()
num+=1
current.setNext(temp)
self.count+=1
def insert(self,index,item):#在固定位置插入元素
current=self.head
temp=Node(item)
previous=None
count=0
while count != index:
previous=current
current=current.getNext()
count+=1
temp.setNext(current)
previous.setNext(temp)
self.count+=1
删除元素
按索引删除和按元素删除
def remove(self,item):#删除item元素
current=self.head
previous=None
found=False
while not found:
if current.getData()==item:
found=True
else:
previous=current
current=current.getNext()
if previous==None:
self.head=current.getNext()
else:
previous.setNext(current.getNext())
self.count -= 1
def pop(self,index = -1):#删除索引index位置的元素,默认为最后一位
current=self.head
previous=None
count=0
if index == -1 :
index = self.count - 1
if index==0:
self.head=current.getNext()
self.count-=1
else:
while count != index:
previous=current
current=current.getNext()
count+=1
previous.setNext(current.getNext())
self.count-=1
return current.getData()#还返回了删除的是哪个元素
切片操作,这里偷懒了,直接复制了一遍链表,然后将不在范围的元素用pop操作删除
def slice(self,start,stop):输入起始和结束的索引
current=self.head
previous=None
count=0
copyList=copy.deepcopy(self)
while count != start:
copyList.pop(0)
count+=1
count=self.count
while count != stop:
copyList.pop()
count-=1
return copyList
好,先弄这么多,已经可以将其当做一个简单的列表来使用了(没有写__iter__所以只能自己遍历),再用这个链表类来实现栈,队列等等,完全可以照搬使用列表时的构建方法。