• 单链表


    # 定义节点
    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()
  • 相关阅读:
    用Github发布静态页面
    JS实现图片放大查看
    CSS3-字体渐变色
    Eclipse切换工作空间(Workspace)
    JS打开新的窗口
    HTML中特殊符号的处理
    PHP转码函数
    SecureCRT按退格键出现^H问题解决
    商人过河问题(二)java实现
    商人过河问题(一)
  • 原文地址:https://www.cnblogs.com/zhangweijie01/p/10229828.html
Copyright © 2020-2023  润新知