数据结构之单向链表

单向链表是一种基础数据结构,每个节点包含数据域和指向下一个节点的链接。链表不连续存储,通过节点间的链接进行访问。本文介绍了单向链表的基本概念,包括如何创建节点、链表操作如添加、删除、查找等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是在每一个节点(数据存储单元)里存放下一个节点的位置信息(即地址)。
在这里插入图片描述
链表可以分为单向链表、单向循环链表、双向链表
单向链表也叫单链表,是链表中最简单的一种形式,它的每个节点包含两个域,一个信息域(元素域)和一个链接域。这个链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值。
在这里插入图片描述
表元素域elem用来存放具体的数据。
链接域next用来存放下一个节点的位置(python中的标识)
变量p指向链表的头节点(首节点)的位置,从p出发能找到表中的任意节点。

创建节点

class Node:
    """创建节点"""
    def __init__(self, item):    
        self.item = item  # item存放数据元素        
        self.next = None  # next 下一个节点的标识

单链表的操作
is_empty() 判断链表是否为空
length() 获取链表长度
travel() 遍历整个链表
add(item) 从链表头部添加元素
append(item) 从链表尾部添加元素
insert(pos, item) 从指定位置添加元素
remove(item) 删除节点
search(item) 查找节点是否存在

class SingleLinkList:
    """单向链表"""
    def __init__(self):
        self._head = None

    def is_empty(self):
        """判断链表是否为空"""
        return self._head == None

    def length(self):
        """返回链表的长度"""
        # 如果链表为空,返回长度0
        if self.is_empty():
            return 0
        count = 1
        # 创建一个游标,指向头节点,从头遍历到尾部
        cur = self._head
        while cur.next != None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        if self.is_empty():
            return
        cur = self._head
        print(cur.item)
        while cur.next != None:
            cur = cur.next
            print(cur.item)
        
    def add(self, item):
        """头部添加节点"""
        # 先创建一个节点,保存item值
        node = Node(item)
   	    # 将新节点的链接域next指向头节点,即_head指向的位置
        node.next = self._head 
        # 将链表的头_head指向新节点
        self._head = node            
                       
	def append(self, item):
        """尾部添加元素"""
        node = Node(item)
        # 先判断链表是否为空,若是空链表,则将_head指向新节点
        if self.is_empty():
            self._head = node
        # 若不为空,则找到尾部,将尾节点的next指向新节点
        else:
            cur = self._head
            while cur.next != None:
                cur = cur.next
            # 将尾节点的next指向新节点   
            cur.next = node
            
    def insert(self, pos, item):
        """
        在指定位置添加节点
        :type pos: int
        :type item: elememt     
        """
        # 若指定位置pos为第一个元素之前,则执行头部插入
        if pos <= 0:
            self.add(item)
        # 若指定位置超过链表尾部,则执行尾部插入
        elif pos > (self.length()-1):
            self.append(item)
        # 链表中的其他位置
        else:        	
            node = Node(item)
            cur = self._head
            count = 0
            # 移动到指定位置的前一个位置
            while count < (pos-1):
                count += 1
                cur = cur.next
            # 插入节点的链接域,指向指定位置的下一个表元素域
            node.next = cur.next
            # 指定位置前一个的链接域,断开原有的链接,指向插入节点的表元素域
            cur.next = node

    def remove(self,item):
        """删除节点"""
        cur = self._head
        pre = None
        while cur != None:
            # 找到指定元素
            if cur.item == item:
                # 如果第一个就是删除的节点
                if not pre:
                    # 将头指针指向头节点的后一个节点
                    self._head = cur.next
                else:
                    # 将删除位置前一个节点的next指向删除位置的后一个节点
                    pre.next = cur.next
                break
            else:
                # 继续按链表后移节点
                pre = cur
                cur = cur.next

    def search(self,item):
        """
        链表查找节点是否存在,返回True或者False
        """
        cur = self._head
        while cur != None:
            if cur.item == item:
                return True
            cur = cur.next
        return False

测试

if __name__ == "__main__":
    res = SingleLinkList()
    res.add(1)
    res.add(2)
    res.append(3)
    res.insert(2, 4)
    print("length:",res.length())
    res.travel()
    print('----------分割线------------')
    print(res.search(3))
    print(res.search(5))
    res.remove(1)
    print("length:",res.length())
    res.travel()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值