编辑代码

class Node(object):
  def __init__(self, val):
    # 存放节点的数据域
    self.val = val  #给定一个元素
    # 指向后继节点的指针
    self.next = None    #设置下一个节点为空

class SingleLinkedList(object):
    def __init__(self):
        '''单链表初始化'''
        # 声明头指针、尾指针均指向空
        self.head = None
        self.tail = None
    def empty(self):
    #判断单链表是否为空 如果单链表为空返回True,否则返回False
        return self.head is None

    def length(self):
    #获取单链表的长度
    # size 用来计算单链表的长度
        size = 0
     # 声明 cur 指针,用来遍历单链表
        cur = self.head
        while cur != None:
            size += 1
            cur = cur.next
        return size

    def travel_list(self):
        '''遍历整个链表,打印每个节点的数据'''
        cur=self.head
        while cur is not None:
            print(cur.val,end=" ")
            cur=cur.next
        print("\n")

    def headinsert(self,val):
        node=Node(val)
        if self.head is not None:
            node.next=self.head
        self.head=node  #把新节点设置为head
    def rearinsert(self,val):
        if self.head is None: #如果这是第一个节点 调用头插法
            self.headinsert(val)
        else:
            cur=self.head
            while cur.next is not None: #遍历到最后一个节点
                cur=cur.next
            cur.next=Node(val) #创建新节点病连接到最后
    def insert(self,pos,val): #指定位置插入元素
        if pos<=0:
            self.headinsert(val)    #<0调用头插法
        elif pos>self.length()-1:   #>length 调用尾插法
            self.rearinsert(val)
        else:
            cur=self.head   
            count=0
            while count<pos-1:      #遍历
                count+=1
                cur=cur.next
            newest=Node(val)
            newest.next=cur.next
            cur.next=newest

    def del_first(self):#删除头节点
        if self.empty():
            raise IndexError('链表为空')
        # 单链表只有一个节点
        if self.length() == 1:
            self.head = None
        # 链表长度大于1
        else:
            self.head = self.head.next
    def del_last(self): #删除尾结点
        if self.empty():
            raise IndexError('链表为空')
        if self.length() == 1:
            self.tail = None
        else:
            pre = self.head
            cur = pre.next
            while  cur.next is not None:
                pre = cur
                cur = cur.next
            cur = None
            pre.next = None
            self.tail = pre

mylist=SingleLinkedList()
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.headinsert(200)
mylist.headinsert(300)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.rearinsert(400)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
print("==========================")
mylist.insert(0,10000)
print(mylist.empty())
print(mylist.length())
mylist.travel_list()
mylist.insert(10,1000)
mylist.insert(2,500)
mylist.travel_list()
mylist.del_first()
mylist.travel_list()
mylist.del_last()
mylist.travel_list()