python单链表(代码)

class Node(object):
    """节点"""

    def __init__(self, item):
        # 用于保存数据
        self.item = item
        # 用于保存下一个节点地址
        self.next = None


class SingleLinkList(object):
    """单链表"""

    def __init__(self):
        # 单链表初始化为空
        self.__head = None

    def is_empty(self):
        return self.__head is None

    def length(self):
        count = 0  # 记录所有节点的数量
        cur = self.__head
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def add(self, item):
        """首位添加"""
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def travel(self):
        """遍历单链表"""
        cur = self.__head
        while cur is not None:
            print(cur.item)
            cur = cur.next

    def append(self, item):
        """链表尾部添加元素"""
        if self.is_empty():
            self.add(item)
        else:
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            node = Node(item)
            cur.next = node

    def insert(self, pos, item):
        """指定位置添加元素"""
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            node = Node(item)
            cur = self.__head
            index = 0
            while index < (pos - 1):
                cur = cur.next
                index += 1
            # 循环结束,当前cur就是要插入元素的前节点
            node.next = cur.next
            # 前节点的next指向插入元素
            cur.next = node

    def remove(self, item):
        """删除节点"""
        cur = self.__head
        pre = None
        while cur is not None:
            if cur.item == item:
                # 要删除的是首节点
                if pre is None:
                    self.__head = cur.next
                else:
                    pre.next = cur.next
            pre = cur
            cur = cur.next

    def search(self,item):
        """查找节点是否存在"""
        cur=self.__head
        while cur is not None:
            if cur.item==item:
                return True
            cur=cur.next
        return False


if __name__ == '__main__':
    slist = SingleLinkList()
    slist.add(1)
    slist.append(4)
    slist.insert(0, 2)
    slist.travel()
    print(slist.search(3))
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值