ACM格式处理链表的输入输出

这里写自定义目录标题

1、定义链表结构体:

struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x): val(x), next(NULL){}
};

2、将输入变成数组,将数组构建成链表:


ListNode* createList(vector<int>& nums){
    if(nums.size() == 0)
        return NULL;
    ListNode* head = new ListNode(nums[0]);
    ListNode* curNode = head;
    for(int i = 1; i < nums.size(); ++i){
        curNode->next = new ListNode(nums[i]);
        curNode = curNode->next;
    }
    return head;
}

3、 这里以题目:合并两个有序链表为例:

#include <bits/stdc++.h>
using namespace std;
struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x): val(x), next(NULL){}
};
ListNode* createList(vector<int>& nums){
    if(nums.size() == 0)
        return NULL;
    ListNode* head = new ListNode(nums[0]);
    ListNode* curNode = head;
    for(int i = 1; i < nums.size(); ++i){
        curNode->next = new ListNode(nums[i]);
        curNode = curNode->next;
    }
    return head;
}
ListNode* MergeTwoListNode(ListNode* l1, ListNode* l2){
    if(!l1)
        return l2;
    if(!l2)
        return l1;
    if(l1->val < l2->val){
        l1->next = MergeTwoListNode(l1->next, l2);
        return l1;
    }
    else{
        l2->next = MergeTwoListNode(l1, l2->next);
        return l2;
    }
}
int main()
{
    vector<int> nums1, nums2;
    int num1, num2;
    while(cin >> num1)
    {
        nums1.push_back(num1);
        if(cin.get() == '\n')
            break;
    }
    while(cin >> num2)
    {
        nums2.push_back(num2);
        if(cin.get() == '\n')
            break;
    }
    ListNode* head1 = createList(nums1);
    ListNode* head2 = createList(nums2);
    ListNode* res = MergeTwoListNode(head1, head2);
    ListNode* p=res;
    while(p)
    {
        cout<<p->val<<" ";
        p=p->next;
    }
    return 0;
}
 
另一种方法,直接放入数组中,可以通过;
#include <bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> nums1, nums2,nums;
    int num1, num2;
    while(cin >> num1)
    {
        nums1.push_back(num1);
        nums.push_back(num1);
        if(cin.get() == '\n')
            break;
    }
    while(cin >> num2)
    {
        nums2.push_back(num2);
        nums.push_back(num2);
        if(cin.get() == '\n')
            break;
    }
    sort(nums.begin(),nums.end());
    for(int i=0;i<nums.size();i++)
        cout<<nums[i]<<" ";
    return 0;
}
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值