LeetCode 021 Merge Two Sorted Lists 混合插入有序链表

链表合并

http://www.nowcoder.com/questionTerminal/46bda7f0570a47b6b54a29a0a6ae4c27

红红火火恍恍惚惚,直接拿LeetCode题来,蘑菇街自己不出题吗?
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>

using namespace std;

class Solution{
public:
    typedef struct Node {
        int data;
        Node * next;
        Node(int x=0, struct Node * next=NULL): data(x), next(next){
        }; 
    } ListNode;
   
    Node * create() {
        int data;
        Node * head = new Node;
        Node * p = head;
        //cout << "Please input the elements of the link list: "<<endl;
        do
        {
            scanf_s("%d", &data);
            Node * temp = new Node(data);
            p->next = temp;
            p = p->next;
        } while (getchar() != '\n');
        head = head->next;
        return head;
    }
    
    Node * mergeLinkNode(Node * list0, Node * list1) {
        Node * newNode = new Node;
        Node * p = newNode;
        while (list0 != NULL && list1 != NULL) {
            if (list0->data < list1->data) {
                p->next = list0;
                list0 = list0->next;
            }
            else {
                p->next = list1;
                list1 = list1->next;
            }
            p = p->next;
        }
        p->next = list0 != NULL ? list0 : list1;
        newNode = newNode->next;
        return newNode;
    }
};


int main() {
    Solution * s = new Solution;
    Solution::Node * list0 = new Solution::Node;
    Solution::Node * list1 = new Solution::Node;
    Solution::Node * list2 = new Solution::Node;
    list0 = s->create();
    list1 = s->create();
    list2 = s->mergeLinkNode(list0, list1);
    while (list2 != NULL) {
        cout << list2->data << " ";
        list2 = list2->next;
    }
    cout << endl;
    return 0;
}


全部评论

相关推荐

爱吃肉的伊登在写日记:好棒,27届简历能做成这个样子,但是第一个项目感觉cover住难度还是不小的,特别是二面的时候肯定要对分布式系统设计这一块儿有高出正常面试者的水平才行
点赞 评论 收藏
分享
04-11 21:31
四川大学 Java
野猪不是猪🐗:(ja)va学弟这招太狠了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务