红红火火恍恍惚惚,直接拿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; }