数据结构:双向链表(四)特定位置添加元素
双向链表的操作
insert(pos,item) 特定位置pos添加元素item
思路:1、当pos<=0的时候,就是头部添加元素,这里用了封装的类,之前写过 url:https://www.cnblogs.com/cong3Z/p/12889535.html
2、当pos超过了当前链表的长度,认为是在链表尾部添加元素,同样之前写过 url: https://www.cnblogs.com/cong3Z/p/12889691.html
3、当pos在链表中间的时候,循环找到该位置,循环条件 count<pos-1;具体操作见代码class Node(object):
def __init__(self,item):
self.item=item
self.prev=None
self.next=None
class DLinkList(object):
def __init__(self):
self.__head=None
def insert(self,pos,item):
if pos<=0:
self.add(item)
if pos>(self.length()-1):
self.append(item)
cur=self.__head
count=0
node=Node(item)
while count <(pos-1):
count=+1
cur=cur.next
node.prev=cur.prev #让node向前指向cur之前的节点(cur就是pos位置)
node.next=cur #让node向后指向cur原来的节点
cur.prev.next=node #让cur之前那个节点向后不再指向cur而是node
cur.prev=node #让cur向前指向node的,而不是继续指想之前的节点

浙公网安备 33010602011771号