【id:21】【20分】A. DS单链表--类实现

该文描述了使用C++编程语言通过类来实现单链表的数据结构,包括头结点,数据域和指针域。链表支持插入、删除和查找操作。示例代码展示了如何创建链表、插入元素、删除元素以及查找元素的功能。

题目描述

用C++语言和类实现单链表,含头结点

属性包括:data数据域、next指针域

操作包括:插入、删除、查找

注意:单链表不是数组,所以位置从1开始对应首结点,头结点不放数据

类定义参考

输入

n

第1行先输入n表示有n个数据,接着输入n个数据

使用实现DS单链表,通常需要定义两个:一个是节点(Node),用于表示链表中的每个节点;另一个是链表(LinkedList),用于管理这些节点。 ### 节点(Node) 节点通常包含两个属性:数据(data)和指向下一个节点的引用(next)。以下是Python实现的节点示例: ```python class Node: def __init__(self, data): self.data = data self.next = None ``` ### 链表(LinkedList) 链表需要实现一些基本的操作,如插入节点、删除节点、查找节点等。以下是Python实现链表示例: ```python class LinkedList: def __init__(self): self.head = None # 在链表尾部插入节点 def insert(self, data): new_node = Node(data) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = new_node # 打印链表 def print_list(self): current = self.head while current: print(current.data, end=" -> " if current.next else "\n") current = current.next # 合并两个链表并去重 def merge_and_remove_duplicates(self, other_list): values = set() current = self.head while current: values.add(current.data) current = current.next other_current = other_list.head while other_current: if other_current.data not in values: self.insert(other_current.data) other_current = other_current.next # 反转链表 def reverse(self): prev = None current = self.head while current: next_node = current.next current.next = prev prev = current current = next_node self.head = prev ``` ### 使用示例 ```python # 创建两个链表 list1 = LinkedList() list1.insert(1) list1.insert(2) list1.insert(3) list2 = LinkedList() list2.insert(2) list2.insert(3) list2.insert(4) # 合并两个链表并去重 list1.merge_and_remove_duplicates(list2) print("合并并去重后的链表:") list1.print_list() # 反转链表 list1.reverse() print("反转后的链表:") list1.print_list() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值