单链表

# 定义节点
class Node():
    def __init__(self,item):
        self.item=item
        self.next=None
# 单链表实现
class SingleLinkList():
    # 定义头节点
    def __init__(self,node=None):
        self.__head=node
    # 判断链表是否为空
    def is_empty(self):
        return self.__head is None
    # 链表长度
    def length(self):
        cur=self.__head
        count=0
        while cur is not None:
            count+=1
            cur=cur.next
        return count
    # 循环链表
    def travel(self):
        cur=self.__head
        while cur is not None:
            print(cur.item,end='')
            cur=cur.next
        print('')
    # 搜索节点
    def search(self,item):
        cur=self.__head
        while cur is not None:
            if cur.item==item:
                return True
            cur=cur.next
        return False
    # 头部增加节点
    def add(self,item):
        node=Node(item)
        node.next=self.__head
        self.__head=node
    # 尾部增加节点
    def append(self,item):
        node=Node(item)
        if self.is_empty():
            self.__head=node
        else:
            cur=self.__head
            while cur.next is not None:
                cur=cur.next
            cur.next=node
    # 指定位置插入
    def insert(self,pos,item):
        node=Node(item)
        if pos<=0:
            self.add(item)
        elif pos>=self.length():
            self.append(item)
        else:
            cur=self.__head
            count=0
            while count<(pos-1):
                cur=cur.next
                count+=1
            node.next=cur.next
            cur.next=node
    # 删除节点
    def remove(self,item):
        cur=self.__head
        pre=None
        while cur is not None:
            if cur.item==item:
                if cur==self.__head:
                    self.__head=cur.next
                else:
                    pre.next=cur.next
                return
            pre=cur
            cur=cur.next
if __name__ == '__main__':
    ll=SingleLinkList()
    for i in range(2):
        ll.append(i)
    print(ll.length())
    ll.travel()
    ll.insert(5,7)
    ll.travel()
    ll.remove(4)
    ll.travel()
posted @ 2019-01-06 18:45  名字到底要多长  阅读(171)  评论(0编辑  收藏  举报