给定一个整数数组 nums,要求 先构建一个链表,然后遍历链表并输出所有元素。
输入共两行:
输出 n 个整数,每个数字占一行,按链表顺序输出。
4
2 7 11 15
2
7
11
15
3
3 2 4
3
2
4
在一些涉及链表的面试题(如翻转、合并、排序链表)时,本题的基础代码可以作为模板。
#include <bits/stdc++.h>
using namespace std;
// 定义链表节点结构
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 创建链表并返回头结点
ListNode* createLinkedList(const vector<int>& nums) {
if (nums.empty()) return nullptr;
ListNode* head = new ListNode(nums[0]);
ListNode* curr = head;
for (size_t i = 1; i < nums.size(); i++) {
curr->next = new ListNode(nums[i]);
curr = curr->next;
}
return head;
}
// 遍历链表并输出
void printLinkedList(ListNode* head) {
ListNode* curr = head;
while (curr) {
cout << curr->val << endl;
curr = curr->next;
}
}
int main() {
int n;
cin >> n; // 读取数组长度
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i]; // 读取数组元素
}
ListNode* head = createLinkedList(nums); // 创建链表
printLinkedList(head); // 遍历链表并输出
return 0;
}
class ListNode:
"""定义链表节点"""
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(nums):
"""根据数组创建链表"""
if not nums:
return None
head = ListNode(nums[0])
curr = head
for num in nums[1:]:
curr.next = ListNode(num)
curr = curr.next
return head
def print_linked_list(head):
"""遍历并输出链表"""
curr = head
while curr:
print(curr.val)
curr = curr.next
# 读取输入
n = int(input()) # 读取数组长度
nums = list(map(int, input().split())) # 读取数组元素
# 创建链表
head = create_linked_list(nums)
# 遍历链表并输出
print_linked_list(head)
import java.util.Scanner;
// 定义链表节点
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Main {
// 创建链表
public static ListNode createLinkedList(int[] nums) {
if (nums.length == 0) return null;
ListNode head = new ListNode(nums[0]);
ListNode curr = head;
for (int i = 1; i < nums.length; i++) {
curr.next = new ListNode(nums[i]);
curr = curr.next;
}
return head;
}
// 遍历并输出链表
public static void printLinkedList(ListNode head) {
ListNode curr = head;
while (curr != null) {
System.out.println(curr.val);
curr = curr.next;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 读取数组长度
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt(); // 读取数组元素
}
ListNode head = createLinkedList(nums); // 创建链表
printLinkedList(head); // 遍历链表并输出
sc.close();
}
}
读取输入:获取数组的长度 n
,然后读取 n
个整数作为数组 nums
。
构建链表
:
head
。next
指针遍历数组,将每个元素转换为 ListNode
并链接起来。遍历并输出链表
:
while
循环遍历链表,每次打印当前节点的值,并移动到下一个节点。