作者 李卫明
单位 杭州电子科技大学
1.3 在第1题( 编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。)建立2个单链表基础上,设计和实现就地逆置单链表函数,即利用原单链表结点建立元素次序相反的单链表。编写程序,建立2个单链表,就地逆置这2个单链表,显示逆置前后的各单链表。注意不可存在内存泄漏。
输入格式:
若干整数。
输出格式:
每个单链表输出占一行,元素间用分隔符分隔;两个初始单链表和两个就地逆置后单链表,4个单链表,共4行。
输入样例:
100 2 3 -2 -8 -6 -9 -10 50 2 -1
输出样例:
2->2->3->50->100
-10->-9->-8->-6->-2->-1
100->50->3->2->2
-1->-2->-6->-8->-9->-10
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++代码:
#include<bits/stdc++.h>
using namespace std;
int main() {
list<int> l1;
list<int> l2;
int x;
while((scanf("%d",&x)) != EOF){
if(x > 0){
if(l1.size()){
if(x >= l1.back()){
l1.push_back(x);
}
else if(x <= l1.front()){
l1.push_front(x);
}
else{
for(list<int>::iterator it=l1.begin();it != l1.end();it++){
if(x < *it){
l1.insert(it,x);
break;
}
}
}
}
else{
l1.push_back(x);
}
}
else if(x < 0){
if(l2.size()){
if(x >= l2.back()){
l2.push_back(x);
}
else if(x <= l2.front()){
l2.push_front(x);
}
else{
for(list<int>::iterator it=l2.begin();it != l2.end();it++){
if(x < *it){
l2.insert(it,x);
break;
}
}
}
}
else{
l2.push_back(x);
}
}
}
for(list<int>::iterator it=l1.begin();it != l1.end();it++){
it == l1.begin() ? cout << *it : cout << "->" << *it;
}
cout << endl;
for(list<int>::iterator it=l2.begin();it != l2.end();it++){
it == l2.begin() ? cout << *it : cout << "->" << *it;
}
cout << endl;
for(auto it=l1.rbegin();it != l1.rend();it++){
it == l1.rbegin() ? cout << *it : cout << "->" << *it;
}
cout << endl;
for(auto it=l2.rbegin();it != l2.rend();it++){
it == l2.rbegin() ? cout << *it : cout << "->" << *it;
}
cout << endl;
l1.clear();
l2.clear();
return 0;
}