剑指offer:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:首先确定输出链表的头result为输入两个链表头中较小的一个。然后不断比较,把输入连个链表中头较小的依次插入输出链表尾部。所以需要一个结点指针end指向输出链表的尾结点。
//#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <math.h>
#include <iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* result,*end;//result为输出链表头,end为输出链表尾。
if(pHead1 == NULL)
return pHead2;
if(pHead2 == NULL)
return pHead1;
if(pHead1 != NULL && pHead2 != NULL)//确定输出头
if(pHead1->val <= pHead2->val){
result = pHead1;
pHead1 = pHead1->next;
}
else{
result = pHead2;
pHead2 = pHead2->next;
}
end = result;//此时头和尾相同
while(pHead1 != NULL && pHead2 != NULL){//不断比较插入尾部,直到一个输入链表为空
if(pHead1->val <= pHead2->val){
end->next = pHead1;//插入尾部
end = end->next;//更新尾部
pHead1 = pHead1->next;//跟新输入链表1的头
}
else{
end->next = pHead2;
end = end->next;
pHead2 = pHead2->next;
}
}
if(pHead1 == NULL)//一个输入链表为空后,直接将另外一个插入输出的尾部,end 不用跟新了
end->next = pHead2;
else
end->next = pHead1;
return result;
}
};
int main()
{
struct ListNode* p1 = (struct ListNode*)malloc(sizeof(struct ListNode));
//struct ListNode* p2 = (struct ListNode*)malloc(sizeof(struct ListNode));
ListNode* p2 = new ListNode(1);
struct ListNode* r = (struct ListNode*)malloc(sizeof(struct ListNode));
p1->val = 0;
p1->next = NULL;
for(int i = 6; i >= 2; i -= 2){
struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
t->val = i;
t->next = p1->next;
p1->next = t;
}
for(int i = 7; i > 1; i -= 2){
struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
t->val = i;
t->next = p2->next;
p2->next = t;
}
Solution s;
r = s.Merge(p1,p2);
while(r != NULL){
cout << r->val << endl;
r = r->next;
}
system("pause");
return 0;
}