python实现·数据结构与算法之单向链表

单向链表定义

单向链表(Single Linked List)也叫单链表,是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素,是链表中最简单的一种形式。链表中的数据是以结点来表示的,每个节点包含两个域,一个元素域(数据元素的映象)和一个链接域,链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值。

节点示意图

单向链表节点示意图

单向链表示意图

单向链表示意图

单向链表的基本操作

  • is_empty() 判断链表是否为空
  • length 链表长度
  • travel() 遍历整个链表,打印元素
  • add(item) 在链表头部添加元素
  • append(item) 在链表尾部添加元素
  • insert(pos, item) 在指定位置插入元素
  • remove(item) 删除元素
  • clear() 清空链表
  • is_contain(item) 判断元素是否存在

Python代码实现

# 节点的实现

class Node(object):
    """单链表的结点"""
    def __init__(self,item):
        # _item存放数据元素
        self.item = item
        # _next是下一个节点的标识
        self.next = None
# 单向链表的实现

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

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

    @property
    def length(self):
        """链表长度"""
        # cur初始时指向头节点
        cur = self._head
        count = 0
        # 尾节点指向None,当未到达尾部时
        while cur is not None :
            count += 1
            # 将cur后移一个节点
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        cur = self._head
        while cur is not None :
            print(cur.item)
            cur = cur.next
        print("")
        
    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 is not None :
                cur = cur.next
            cur.next = node
            
    def insert(self, pos, item):
        """指定位置添加元素"""
        # 若指定位置pos为第一个元素之前,则执行头部插入
        if pos <= 0:
            self.add(item)
        # 若指定位置超过链表尾部,则执行尾部插入
        elif pos > (self.length-1):
            self.append(item)
        # 找到指定位置
        else:
            node = Node(item)
            count = 0
            # pre用来指向指定位置pos的前一个位置pos-1,初始从头节点开始移动到指定位置
            pre = self._head
            while count < (pos-1):
                count += 1
                pre = pre.next
            # 先将新节点node的next指向插入位置的节点
            node.next = pre.next
            # 将插入位置的前一个节点的next指向新节点
            pre.next = node
            
    def remove(self,item):
        """删除节点"""
        cur = self._head
        pre = None
        while cur is not 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 is_contain(self,item):
        """链表查找节点是否存在,并返回True或者False"""
        cur = self._head
        while cur is not None :
            if cur.item == item:
                return True
            cur = cur.next
        return False
    
    def __len__(self):
        """可以使用len()方法获取链表长度"""
        return self.length
    
    def __iter__(self):
        """可使用循环遍历链表里的元素"""
        cur = self._head
        while cur is not None:
            value = cur.item
            cur = cur.next
            yield value
    
    def __contains__(self, item):
        """可使用in判断是否在链表中"""
        cur = self._head
        while cur is not None :
            if cur.item == item:
                return True
            cur = cur.next
        return False
# 测试数据

if __name__ == '__main__':
    print("--------创建单向链表---------")
    sl_list = SingleLinkList()
    sl_list.add(1)
    sl_list.add(2)
    sl_list.append(3)
    sl_list.insert(2, 4)
    print("length:",len(sl_list))
    sl_list.travel()
    print(sl_list.is_contain(3))
    print(sl_list.is_contain(5))
    print(3 in sl_list)
    print(5 in sl_list)
    sl_list.remove(1)
    print("length:",len(sl_list))
    sl_list.travel()
    print("--------循环遍历-------")
    for i in sl_list:
        print(i)
# 输出结果

--------创建单向链表---------
length: 4
2
1
4
3

True
False
True
False
length: 3
2
4
3

--------循环遍历-------
2
4
3

算法分析

操作复杂度
访问元素 O ( n ) O(n) O(n)
在头部插入/删除 O ( 1 ) O(1) O(1)
在尾部插入/删除 O ( n ) O(n) O(n)
在中间插入/删除 O ( n ) O(n) O(n)

联系我们

个人博客网站:http://www.bling2.cn/

Github地址:https://github.com/lb971216008/Use-Python-to-Achieve

知乎专栏:https://zhuanlan.zhihu.com/Use-Python-to-Achieve

小专栏:https://xiaozhuanlan.com/Use-Python-to-Achieve

博客园:https://www.cnblogs.com/Use-Python-to-Achieve
关注微信公众号【不灵兔】,获取更多资料

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南风以南

如给您带来些许明朗,赏一杯香茗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值