• 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()
  • 相关阅读:
    微服务定义及.Net Core中用的技术
    IPad分屏,当电脑第二显示屏
    .net Core1.0 邮件发送
    AutoMapper总结
    02-C#(基础)基本的定义和说明
    01-.Net编程机制
    C#基础篇--静态成员、抽象成员、接口
    C#基础篇--面向对象(类与对象)
    期末总结
    改动后的封装
  • 原文地址:https://www.cnblogs.com/ClarenceSun/p/14766016.html
Copyright © 2020-2023  润新知