7-12 程序设计综合实践 1.3

作者 李卫明

单位 杭州电子科技大学

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;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值