class Node():
def __init__(self,value=None,next=None):
self._value=value
self._next=next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value=new_value
def setNext(self,new_next):
self._next=new_next
class LinkedList():
def __init__(self):
self._head=Node()
self._tail=None
self._length=0
def isEmpty(self):
return self._head==None
def add(self,value):
'''
在表前端添加元素
:param value: 添加元素的值
:return:
'''
newnode=Node(value,None)
newnode.setNext(self._head)
self._head=newnode
def append(self,value):
'''
在链表的尾部添加元素
:param value:
:return:
'''
newnode=Node(value)
if self.isEmpty():
self._head=newnode
else:
current=self._head
while current.getNext()!=None:
current=current.getNext()
current.setNext(newnode)
def search(self,value):
'''
查找链表中是否有该元素
:param value: 元素
:return: True or False
'''
current=self._head
while current!=None :
if current.getValue()==value:
return True
else:
current=current.getNext()
return False
def index(self,value):
'''
索引元素在列表中的位置
:param value: 元素的值
:return: 元素在列表中的索引
'''
current=self._head
count=0
while current!=None:
if current.getValue()==value:
return count
else:
count+=1
current=current.getNext()
return ValueError('%s is not in linkedlist'%value)
def remove(self,value):
'''
删除链表第一个值为value的元素
:param value:要删除的元素的值
:return:
'''
current=self._head
pre=None
while current!=None:
if current.getValue()==value:
if not pre:
self._head=current.getNext()
else:
pre.setNext(current.getNext)
break
else:
pre=current
current=current.getNext()
def size(self):
'''
返回数组的长度
:return: 数组的长度
'''
current=self._head
count=0
while current!=None:
count+=1
current=current.getNext()
return count
def insert(self,pos,value):
'''
在指定位置中插入元素
:param pos: 插入位置
:param value:插入的值
:return:None
'''
if pos<=1:
self.add(value)
elif pos>self.size()-1:
self.append(value)
else:
temp=Node(value)
count=1
pre=None
current=self._head
while count<pos:
count+=1
pre=current
current=current.getNext()
pre.setNext(temp)
temp.setNext(current)