20170912_归并两个已经排好序的单链表

来源:互联网 发布:linux时间同步 编辑:程序博客网 时间:2024/06/08 11:23

20170912_归并两个已经排好序的单链表


//21. Merge Two Sorted Lists /** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */#include<iostream>#include<vector>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int x):val(x),next(nullptr) {}};ListNode *CreatList(ListNode * &root, vector<int> &a){int n=a.size();if(n==0)return root=nullptr;else{root=new ListNode(a[0]);ListNode *r=root;for(int i=1; i<n; ++i){ListNode *s=new ListNode(a[i]) ;r->next=s;r=s;}return root;}}void OutList(ListNode *root){ListNode *p=root;if(p==nullptr)return;else{while(p != nullptr){if(p->next != nullptr)cout<<p->val<<",";elsecout<<p->val;p=p->next;}cout<<endl;}}class Solution{public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2){        ListNode *root=merge(l1,l2);return root;    }//对两个有序的的单链表进行 一次归并ListNode *merge(ListNode *head1, ListNode *head2){ListNode *temp=new ListNode(0);ListNode *p=temp;while(head1 != nullptr && head2 != nullptr){if(head1->val <= head2->val){p->next=head1;head1=head1->next;}else{p->next=head2;head2=head2->next;}p=p->next;}if(head1 != nullptr)p->next=head1;if(head2 != nullptr)p->next=head2;p=temp->next;temp->next=nullptr;delete temp;return p;}};int main(){vector<int> a1,a2;int ch;cout<<"按照顺序输入单链表1节点数据:"<<endl;while(cin>>ch)a1.push_back(ch);cin.clear();cin.sync();//清楚缓冲ListNode *r;ListNode *root1=CreatList(r,a1);cout<<"单链表1建立完成."<<endl;cout<<"顺序输出单链表1:"<<endl;OutList(root1);cout<<"顺序输出单链表1完成."<<endl;cout<<"按照顺序输入单链表2节点数据:"<<endl;//cin.clear();while(cin>>ch)a2.push_back(ch);ListNode *root2=CreatList(r,a2);cout<<"单链表2建立完成."<<endl;cout<<"顺序输出单链表2:"<<endl;OutList(root2);cout<<"顺序输出单链表2完成."<<endl;//cout<<"逆置该单链表:"<<endl;//ListNode *root2=ConvertList(root);//cout<<"输出逆置后的单链表:"<<endl;//OutList(root2);//cout<<"逆置后的单链表输出完成."<<endl;Solution example;ListNode *root=example.mergeTwoLists(root1,root2);OutList(root);system("pause");return 0;}



原创粉丝点击