链表的基本操作

第1关:删除链表元素

任务描述
本关任务:给定程序中已建立一个带有头结点的单向链表,在main函数中将多次调用fun函数,每调用一次fun函数,输出链表尾部结点中的数据,并释放该结点,使链表缩短。 请在指定位置填写代码,使程序得出正确的结果。请不要增行或删行,或更改程序的结构。

相关知识
相关知识略

编程要求
请仔细阅读右侧代码,结合相关知识,在右边提示区域内进行代码补充,完成编写删除链表元素的小程序。

测试说明
平台会对你编写的代码进行测试:

预期输出:
输出每次删除的链表尾部数据。
输出当前链表数据。

开始你的任务吧,祝你成功!

#include <stdio.h> 
#include <stdlib.h> 
#
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
链表是一种常见的数据结构,它由一系列节点组成,每个节点都包含一个值和一个指向下一个节点的指针。 在Python中,我们可以使用类来表示链表和节点。 首先,我们定义一个节点类: ```python class Node: def __init__(self, value): self.value = value self.next = None ``` 然后,我们定义一个链表类,包含一些基本操作: 1. 初始化链表 ```python class LinkedList: def __init__(self): self.head = None ``` 2. 在链表头部插入节点 ```python def insert_at_head(self, value): new_node = Node(value) new_node.next = self.head self.head = new_node ``` 3. 在链表尾部插入节点 ```python def insert_at_tail(self, value): new_node = Node(value) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = new_node ``` 4. 在指定位置插入节点 ```python def insert_at_position(self, position, value): if position <= 0: self.insert_at_head(value) else: new_node = Node(value) count = 0 current = self.head while current and count < position - 1: current = current.next count += 1 if not current: raise IndexError("Position out of range") new_node.next = current.next current.next = new_node ``` 5. 删除指定值的节点 ```python def delete(self, value): if not self.head: return if self.head.value == value: self.head = self.head.next return current = self.head while current.next: if current.next.value == value: current.next = current.next.next return current = current.next ``` 6. 打印链表 ```python def print_list(self): current = self.head while current: print(current.value, end=" ") current = current.next print() ``` 以上就是链表基本操作,你可以根据需要进行调用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ssaty.

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值