zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    处理接口返回script标签对
    跨域问题总结
    CordMirror 在线代码编辑器
    解决IOS移动端 new Date 为 Invalid Date bug
    大屏数据可视化
    Xcode清理缓存
    ArrayMap和HashMap区别
    javacript总结
    css总结
    html总结
  • 原文地址:https://www.cnblogs.com/ClarenceSun/p/14766016.html
Copyright © 2011-2022 走看看