zoukankan      html  css  js  c++  java
  • 2019.9.15单链表的判断/长度/遍历/与尾部添加节点的代码实现

    # coding:utf-8


    class Node(object):
    """節點0"""
    def __init__(self, elem):
    self.elem = elem
    self.next = None

    # node = None(100)
    class SingleLinkList(object):
    """單鏈表"""
    def __init__(self, node=None):
    self._head = node

    def is_empty(self):
    """鏈表是否爲空"""
    return self._head == None

    def length(self):
    """鏈表長度"""
    # cur遊樸,用來移動遍歷節點
    cur = self._head
    # count記錄數量
    count = 0
    while cur != None:
    count += 1
    cur = cur.next
    return count

    def travel(self):
    """遍歷整個鏈表"""
    cur = self._head
    while cur != None:
    print(cur.elem)
    cur = cur.next


    def add(self, item):
    """鏈表頭部添加元素"""
    pass

    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):
    """指定位置添加元素"""
    pass

    def remove(self, item):
    """刪除節點"""
    pass

    def search(self, item):
    """查找節點是否存在"""
    pass


    if __name__ == "__main__":
    ll = SingleLinkList()
    print(ll.is_empty())
    print(ll.length())

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


    ll.append(2)
    ll.append(3)
    ll.append(4)
    ll.append(5)
    ll.append(6)
    ll.travel()

     

     

     

     代码实现效果

     

  • 相关阅读:
    [翻译] DBCamera 轻量级定制摄像头
    使用正则表达式寻找字符串中出现了几个[***]样式的字符串
    [转] iOS文字排版(CoreText)那些事儿
    辉光的UIView
    html5全局属性
    meta你到底了解多少
    原生APP与移动Web App的比较
    Web App开发入门
    web移动开发最佳实践之html篇
    MVC中的扩展点(六)ActionResult
  • 原文地址:https://www.cnblogs.com/lishuide/p/11521718.html
Copyright © 2011-2022 走看看