算法通关村第一关-青铜-单链表基础

本文介绍了单链表的概念,包括链表元素(结点)的定义,如包含元素值和指向下个元素的指针。接着,展示了如何使用Python创建单链表类`SingleLinkList`,并提供了添加元素(头插法、尾插法、中间插入)、删除元素(按值、按位置)、查询元素及修改元素值等基本操作的方法。此外,文章还强调了处理链表为空和超出范围等特殊情况的注意事项。
摘要由CSDN通过智能技术生成

一、认识单链表

1. 链表元素(结点)

链表元素包含有 元素值 和 指向下一个元素的指针

# 链表元素的定义

class Node:
    def __init__(self, elem):
        self.elem = elem
        self.next = None

2. 单链表

由一个个链表元素构成,最后一个元素的next指向 None

 

class SingleLinkList:
    """单链表"""

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

二、单链表的基本操作

基本操作:创建+增删改查

1. 列表创建

from node import Node
from single_link_list import SingleLinkList

if __name__ == '__main__':
    head = Node(1)
    node2 = Node(2)
    node3 = Node(3)

    head.next = node2
    node2.next = node3

    sll = SingleLinkList(head)

2. 增加

增加至头部 | 增加至尾部 | 增加至中间

from node import Node


class SingleLinkList:
    def __init__(self, head):
        self.__head = head

    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 is_empty(self):
        return self.__head is None

    def insert(self, pos, item):
        # 添加链表至中间,链表插入
        """
        link_list: 0 1 2 3 4 5  position 1~6 new_load.val=x
        1. 在链表的头部插入 position=1 => x 0 1 2 3 4 5
        2. 在链表的中间插入 position=4 插入2-3之间 => 0 1 2 x 3 4 5
        3. 在链表的尾部插入 position=7 => 0 1 2 3 4 5 x
        4. 超出范围,不合法 position<1 or position>7
        """
        length = self.length()
        if pos < 1 or pos > length + 1:
            raise ValueError(f"position {pos} is out of range")
        elif pos == 1:
            self.add(item)
        elif pos == length + 1:
            self.append(item)
        else:
            node = Node(item)
            index = 1
            cur = self.__head
            while index < pos - 1:
                index += 1
                cur = cur.next
            node.next = cur.next
            cur.next = node

    def length(self):
        """链表长度"""
        cur = self.__head
        count = 0
        while cur:
            count += 1
            cur = cur.next
        return count

3. 删除

注意特殊情况:链表为空,删除首元素

    def remove_item(self, item):
        """删除节点"""
        cur = self.__head
        pre = None
        while cur:
            if cur.item == item:
                # 如果第一个就是删除的节点
                if not pre:
                    self.__head = cur.next
                else:
                    pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next

    def remove_pos(self, pos):
        """
        删除节点(位置)
        link_list: 0 1 2 3 4 5  position 1~6
        1. 删除链表头部 position=1 => 1 2 3 4 5
        2. 删除链表中间 position=4 => 0 1 2 4 5
        3. 删除链表尾部 position=6 => 0 1 2 3 4
        4. 超出范围,不合法 position<1 or position>6
        """
        if self.is_empty():
            return
        length = self.length()
        if pos < 1 or pos > length:
            raise ValueError(f"position {pos} is out of range")
        if pos == 1:
            self.__head = self.__head.next
        pre_node = self.__head
        index = 1
        while index < pos - 1:
            index += 1
            pre_node = pre_node.next
        cur_node = pre_node.next
        pre_node.next = cur_node.next

4. 修改

修改节点值,替换节点

5. 查询

获取链表长度,查找元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值