请问我这样写错误出在哪里了,为什么运行时开头和结尾顺序会出错呢?
#include
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode *p1=l1,*p2=l2;
ListNode *q1=l1,*q2=l2;
int flag1 = 0,flag2=0,m=0;
if(p1->val<=p2->val)
m=1;
while(p1->next&&p2->next)
{
if(p1->val<=p2->val) {
if(flag1){
q2->next=p1;
flag1 = 0;
}
q1=p1;
p1=p1->next;
}
else{
q1->next=p2;
q2=p2;
flag1 = 1;
p2=p2->next;
}
}
if(p1->next) p2->next=p1;
else p1->next=p2;
if(m) return l1;
else return l2;
}
};
int main(){
Solution a;
ListNode *b = new ListNode;
ListNode *q = b;
for(int i=0;i<20;i+=2){
ListNode *p1 = new ListNode;
p1->next = NULL;
q->next = p1;
p1->val = i;
q = q->next;
}
ListNode *c = new ListNode;
ListNode *qc = c;
for(int i=1;i<=20;i+=2){
ListNode *p1 = new ListNode;
p1->next = NULL;
qc->next = p1;
p1->val = i;
qc = qc->next;
}
b->val = 1;c->val=2;
for(ListNode* y = a.merge(b,c);y;y=y->next){
cout << y->val << " ";
}
return 0;
}