问题描述
题目描述
构建一个单向链表,链表中包含一组整数数据。输出链表中的所有元素。
要求:
1. 使用自定义的链表数据结构
2. 提供一个 linkedList 类来管理链表,包含构建链表和输出链表元素的方法
3. 在 main 函数中,创建一个包含一组整数数据的链表,然后调用链表的输出方法将所有元素打印出来
输入描述
包含多组测试数据,输入直到文件尾结束。
每组的第一行包含一个整数 n,表示需要构建的链表的长度。
接下来一行包含 n 个整数,表示链表中的元素。
输出描述
每组测试数据输出占一行。
按照顺序打印出链表中的元素,用空格隔开,最后一个元素后没有空格。
输入示例
5
1 2 3 4 5
6
3 4 5 6 7 8
输出示例
1 2 3 4 5
3 4 5 6 7 8
提示信息
数据范围:
1 <= n <= 1000;
python解法
# 链表节点类
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 链表类
class LinkList:
def __init__(self):
self.head_node = None
self.length = 0
# 在尾部插入链表节点
def insert(self, data):
self.length += 1
new_node = Node(data)
if self.head_node is None:
self.head_node = new_node
return self.head_node
current_node = self.head_node
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
return new_node
# 打印链表节点
def print_link_list(self):
current_node = self.head_node
while current_node is not None:
print(current_node.data, end=" ")
current_node = current_node.next
print()
while True:
try:
n = int(input())
elements = list(map(int, input().split()))
except:
break
# 新建列表
link_list = LinkList()
# 将数据插入到链表节点中
for data in elements:
link_list.insert(data)
# 打印链表数据
link_list.print_link_list()
C++解法
# include<iostream>
// 定义一个链表节点
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr){}
};
int main(){
int n, val;
// 定义虚拟头节点
ListNode *dummyHead = new ListNode(0);
while (std::cin >> n){
// 定义一个临时变量来构建链表
ListNode *cur = dummyHead;
for (int i = 0; i < n; i++){
std::cin >> val;
// 根据读取的 val 值创建一个新的链表节点
ListNode *newNode = new ListNode(val);
// 将新节点接入链表
cur->next = newNode;
// cur指向下一个节点
cur = cur->next;
}
cur = dummyHead;
// 遍历链表节点并逐个输出
while (cur->next != NULL){
std::cout << cur->next->val << " ";
cur = cur->next;
}
std::cout << std::endl;
}
}