R7-6 单链表的创建及遍历
读入n值及n个整数,建立单链表并遍历输出。
输入格式:
读入n及n个整数。
输出格式:
输出n个整数,以空格分隔(最后一个数的后面没有空格)。
输入样例:
在这里给出一组输入。例如:
2
10 5
输出样例:
在这里给出相应的输出。例如:
10 5
#include <iostream>
using namespace std;
// 定义单链表节点结构
struct ListNode {
int data;
ListNode* next;
ListNode(int val) : data(val), next(nullptr) {}
};
// 函数用于创建链表
ListNode* createLinkedList(int n) {
if (n <= 0) return nullptr;
int value;
cin >> value;
ListNode* head = new ListNode(value);
ListNode* current = head;
for (int i = 1; i < n; ++i) {
cin >> value;
current->next = new ListNode(value);
current = current->next;
}
return head;
}
// 函数用于遍历并输出链表
void printLinkedList(ListNode* head) {
ListNode* current = head;
bool first = true;
while (current != nullptr) {
if (!first) {
cout << " ";
}
cout << current->data;
current = current->next;
first = false;
}
cout << endl;
}
// 主函数
int main() {
int n;
cin >> n;
ListNode* head = createLinkedList(n);
printLinkedList(head);
// 释放链表内存
ListNode* current = head;
while (current != nullptr) {
ListNode* next = current->next;
delete current;
current = next;
}
return 0;
}