算法笔记练习 题解合集
题目
题目描述
根据一个整数序列构造一个单链表,然后将其反转。
例如:原单链表为 2 3 4 5 ,反转之后为5 4 3 2
输入
输入包括多组测试数据,每组测试数据占一行,第一个为大于等于0的整数n,表示该单链表的长度,后面跟着n个整数,表示链表的每一个元素。整数之间用空格隔开
输出
针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开。如果链表为空,则只输出一行,list is empty
样例输入
5 1 2 3 4 5
0
样例输出
1 2 3 4 5
5 4 3 2 1
list is empty
思路
练习一下头插法反转链表。记得输出反转前的元素。
代码
#include <iostream>
struct Lnode {
int data;
Lnode *next;
};
void initLinklist(Lnode *&head, int n) {
Lnode *tail = head;
while (n--) {
Lnode *p = new Lnode;
scanf("%d", &(p->data));
tail->next = p;
p->next = nullptr;
tail = p;
}
}
void reverseLinklist(Lnode *&head) {
Lnode *p = head->next, *q;
head->next = nullptr;
while (p) {
q = p->next;
p->next = head->next;
head->next = p;
p = q;
}
}
void showLinklist(Lnode *&head) {
Lnode *p = head->next;
if (p) {
while (p) {
if (p != head->next)
putchar(' ');
printf("%d", p->data);
p = p->next;
}
putchar('\n');
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (n == 0) {
puts("list is empty");
continue;
}
Lnode *head = new Lnode;
head->next = nullptr;
initLinklist(head, n);
showLinklist(head);
reverseLinklist(head);
showLinklist(head);
}
return 0;
}