###打卡,带头节点版本的单链表(Python实现)
Day 13 :访问链表第i个节点
依然考虑到新接触链表的朋友不习惯使用它,本次作业还是强化下链表的基本操作。
class Node:
def __init__(self,x=None):
self.value=x
self.next=None
class SingleLinkedList:
#带头节点版本的单链表
def __init__(self):
self.head=Node()
def is_empty(self):
#判空
return self.head.next==None
def size(self):
#长度
#指向头节点下一个,即第一个节点
cur=self.head.next
count=0
while cur!=None:
count+=1
cur=cur.next
return count
def print_all(self):
#打印
cur=self.head.next
while cur!=None:
print(cur.value)
cur=cur.next
print(' ')
def add(self,value):
#头插
node=Node(value)
node.next=self.head.next
self.head.next=node
def append(self,value):
#尾插
if self.is_empty():
self.add(value)
else:
node=Node(value)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
def insert(self,pos,value):
# 指定位置插入
if pos<=0:
self.add(value)#调用头插
elif pos>self.size()-1:
self.append(value)#调用尾插
else:
node=Node(value)
count=0
cur=self.head
while count<pos-1:
cur=cur.next
count+=1
node.next=cur.next
cur.next=node
def get_index(self,index):
#获取index下标位置元素
if self.size()>index>=0:
cur=self.head.next
pos=0
while pos<index:
cur=cur.next
pos+=1
return cur.value
else:
return 'index_error'
def delet_index(self,index):
#删除index下标位置元素
if self.size()>index>=0:
cur=self.head.next
pos=0
while pos<index-1:
cur=cur.next
pos+=1
cur.next=cur.next.next
else:
return 'index_error'
if __name__ == "__main__":
li = SingleLinkedList()
li.add(3)
li.add(2)
li.add(1)
li.append(4)
print(li.get_index(3))
li.delet_index(1)
li.print_all()