python实现单单链表

# -*- 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()

posted @ 2018-09-29 00:15  公众号python学习开发  阅读(209)  评论(0编辑  收藏  举报