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

猜你喜欢

转载自blog.csdn.net/PETERPARKERRR/article/details/122806763