1. 程式人生 > >python實現單單鏈表

python實現單單鏈表

war 是否 utf append emp auth 添加 pychar sea

# -*- coding: utf-8 -*-
# @Time : 2018/9/28 22:09
# @Author : cxa
# @File : node.py
# @Software: PyCharm
# 單向列表
# 數據元素區,下一個結點的鏈接區
# 尾節點指向的結點為空。
"""
表元素域   下一結點鏈接域
"""


class Node:
    # 結點類
    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingLinkList(object):
    # 鏈表類

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

    def is_empty(self):
        """列表是否為空"""
        return self.__head == None

    def length(self):
        """結點的數目,到尾節點截止。需要一個遊標、來記錄當前的位置"""
        cur = self.__head
        """count記錄數量,如果空鏈表也可以正確處理"""
        count = 0
        """開始遊標移動"""
        while cur:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍歷列表"""
        cur = self.__head
        while cur:
            print("當前的結點", cur.elem, end=‘‘)
            cur = cur.next

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

    def insert(self, pos, item):
        node = Node(item)
        ‘‘‘
        從指定位置添加
        :param pos: 從0開始
        :param item: 
        :return: 
        ‘‘‘
        if pos <= 0:
            self.add(item)
        elif pos > self.length(item) - 1:
            self.append(item)
        else:
            pre = self.__head  # pre指前一個對象
            count = 0
            while count < pos - 1:
                count += 1
                pre = pre.next
            # pre指向poss-1
            node.next = pre.next
            pre.next = node

    def remove(self, item):
        """刪除結點"""
        # pre.next=pre.next.next
        cur = self.__head
        pre = None
        while cur:
            if cur.elem == item:
                # 判斷此節點是否是頭節點
                # 頭節點
                if cur == self.__head:
                    self.__head = cur.next
                else:
                    pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next

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


if __name__ == ‘__main__‘:
    # 測試下正確性
    ll = SingLinkList()
    print(ll.is_empty())
    print(ll.length())
    ll.append(1)
    print(ll.is_empty())
    print(ll.length())
    ll.append(2)
    ll.append(3)
    ll.add(8)
    ll.append(4)
    ll.travel()

python實現單單鏈表