zoukankan      html  css  js  c++  java
  • 单链表

    # 定义节点
    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()
  • 相关阅读:
    【转】dip,px,pt,sp 的区别
    JAVA中报错 : org.springframework.beans.factory.BeanCreationException
    ExecuteNonQuery及对比
    ParameterDirection参数类型
    WinForm控件组合使用
    DataGridView控件内实现修改与删除
    DataView筛选绑定
    动态反射
    反射属性名和属性值
    接口与抽象类
  • 原文地址:https://www.cnblogs.com/zhangweijie01/p/10229828.html
Copyright © 2011-2022 走看看