C++s合并两个链表(牛客剑指offer)

/////这段代码不忍直视,想不通这样在牛客剑指offer上都可以通过.。#include <iostream>using namespace std;struct ListNode{int val;struct ListNode *next;ListNode(int x):val(x),next(NULL){}};void show(ListNode *root);class Solution {public:ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ListNode *root=NULL;ListNode *p = pHead1;ListNode *q = pHead2;ListNode *m = NULL;ListNode *n = NULL;if(p==NULL)return q;if(q==NULL)return p;while(p!=NULL && q!=NULL){if(p->val>q->val){n=q->next;if(root==NULL){root = new ListNode(q->val);}else{ListNode *k = root;//m=NULL;ListNode *s = new ListNode(q->val);while(k!=NULL){m=k;k=k->next;}if(m!=NULL){m->next=s;//m=s;}}delete q;q=n;}else{n=p->next;if(root==NULL){root = new ListNode(p->val);}else{//m=NULL;ListNode *k = root;ListNode *s = new ListNode(p->val);while(k!=NULL){m=k;k=k->next;}if(m!=NULL){m->next=s;//m=s;}}delete p;p=n;}}m=root;if(q==NULL){while(m!=NULL){n=m;m=m->next;}n->next=p;}if(p==NULL){while(m!=NULL){n=m;m=m->next;}n->next=q;}//show(root);return root;}};void show(ListNode *root){ListNode *p = root;while(p!=NULL){cout<<p->val<<" ";p=p->next;}cout<<endl;}int main(){ListNode *p1 = new ListNode(1);ListNode *p2 = new ListNode(3);ListNode *p3 = new ListNode(5);p1->next = p2;p2->next = p3;show(p1);ListNode *p4 = new ListNode(2);ListNode *p5 = new ListNode(4);ListNode *p6 = new ListNode(6);p4->next = p5;p5->next = p6;show(p4);Solution sl;ListNode* n = sl.Merge(p1,p4);show(n);return 0;}

,偶尔,我一个人站在黄昏的荒野,

C++s合并两个链表(牛客剑指offer)

相关文章:

你感兴趣的文章:

标签云: