• python-单向链表


    # coding:utf-8

    class Node(object):
    def __init__(self, elem):
    self.elem = elem
    self.next = None


    class SingleLinkList(object):
    def __init__(self, node=None):
    self.__head = node

    """单链表"""

    def is_empty(self):
    """判断链表是否为空"""
    return self.__head == None

    def length(self):
    cur = self.__head
    count = 0
    while cur != None:
    count += 1
    cur = cur.next
    return count

    def travel(self):
    """遍历整个链表"""
    cur = self.__head
    while cur != None:
    print("%s" % (cur.elem), end=" ")
    cur = cur.next
    print("")

    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 != None:
    cur = cur.next
    cur.next = node

    def insert(self, pos, item):
    """指定位置添加元素"""
    if pos <= 0:
    self.add(item)
    elif pos > self.length() - 1:
    self.append(item)
    else:
    pre = self.__head
    count = 0
    while count < pos - 1:
    count += 1
    pre = pre.next
    node = Node(item)
    node.next = pre.next
    pre.next = node

    def remove(self, item):
    """删除节点"""
    cur = self.__head
    pre = None
    while cur!=None:
    if cur.elem == item:
    if cur == self.__head:
    self.__head = cur.next
    else:
    pre.next = cur.next
    print(item,"已经删除")
    return True
    else:
    pre = cur
    cur = cur.next
    print("不存在此节点",item)
    return False


    def search(self, item):
    """查找节点是否存在"""
    cur = self.__head
    while cur != None:
    if cur.elem == item:
    return True
    else:
    cur = cur.next
    return False


    if __name__ == '__main__':
    sll = SingleLinkList()
    print(sll.is_empty())
    print(sll.length())

    sll.append(1)
    print(sll.is_empty())
    print(sll.length())

    sll.add(8)
    sll.append(2)
    sll.append(3)
    sll.travel()
    sll.insert(-1,9)
    sll.travel()
    sll.insert(2,100)
    sll.travel()
    sll.insert(10,200)
    sll.travel()
    sll.remove(100)
    sll.travel()
    sll.remove(9)
    sll.travel()
    sll.remove(900)
    sll.remove(200)
    sll.travel()
    sll.remove(8)
    sll.travel()
    sll.remove(1)
    sll.remove(2)
    sll.travel()
    sll.remove(3)
    sll.travel()
    sll.remove(2000)
    sll.travel()
  • 相关阅读:
    ajax
    vue 思維導圖
    python项目_log日志的使用
    mysql数据库_serialisers
    常见的时间复杂度及其增长速度比较
    C++中的sort()函数
    用C++实现输入三个整数,中间用逗号隔开
    python——递归函数
    python——函数
    python——可变对象和不可变对象
  • 原文地址:https://www.cnblogs.com/ClarenceSun/p/14766016.html
Copyright © 2020-2023  润新知