单链表的操作
insert(pos, item) 指定位置添加元素
思路:1、当pos<0的时候,我们将其视为在头部添加元素
2、当pos远大于整个链表的长度,我们将视为在尾部添加元素
3、中间添加时,我们应该先让新节点的next指向原来pos处的节点,即node.next=(pos-1).next,而pos使pos-1处节点指向新的节点 (pos-1.next)=node
class SingleNode(object): #单链表节点
def __init__(self,item):
self.item=item
self.next=None
class SingleLinkList(object):
def __init__(self):
self._head=Nonde
def add(self,item): #头部添加元素
node=SingleNode(item)
node.next=self._head
self._head=node
def append(self,item): #尾部添加元素
node=SingleNode(item)
if self._head==None:
self._head=node
else:
cur=self._head
node=SingleNode(item)
while cur!=None :
cur=cur.next
cur.next=node
def length(self): #单链表的长度
cur=self._head
count=0
while cur!=None:
count=count+1
cur=cur.next
return count
def insert(pos,item): #特定位置插入元素
if pos<=0:
self.add(item)
elif pos>(self.length()-1):
self.append(item)
else:
cur=self._head
count=0
while count<(pos-1):
cur=cur.next
count=count+1
node=SingleNode(item)
node.next=cur.next
cur.next=node