#include <iostream>
#include <limits>
#include <vector>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* Create(vector<int> da) {
if (da.empty()) return NULL;
ListNode* head = new ListNode(da[0]);
ListNode* cur = head;
for (int i=1; i<da.size(); ++i) {
ListNode* a = new ListNode(da[i]);
cur->next = a;
cur = cur->next;
}
return head;
}
void PrintList(ListNode* head) {
while(head) {
std::cerr << head->val << " ";
head = head->next;
}
std::cerr << std::endl;
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1) return pHead2;
if (!pHead2) return pHead1;
ListNode* head = pHead1;
ListNode* per = NULL;
ListNode* net = NULL;
while (pHead1 && pHead2) {
if (pHead1->val <= pHead2->val) {
per = pHead1;
pHead1 = pHead1->next;
} else {
net = pHead2->next;
per->next = pHead2;
pHead2->next = pHead1;
pHead2 = net;
}
}
if (!pHead1) per->next = pHead2;
return head;
}
ListNode* ReverseList(ListNode* head) {
if (head == NULL) {
return NULL;
}
ListNode *per = NULL, *cur = head, *net = head->next;
while (net != NULL) {
cur->next = per;
per = cur;
cur = net;
net = cur->next;
}
cur->next = per;
return cur;
}
};
int main()
{
vector<int> da{1,3,5};
vector<int> db{2,4,6};
Solution s;
ListNode* head1 = s.Create(da);
ListNode* head2 = s.Create(db);
s.PrintList(head1);
s.PrintList(head2);
s.PrintList(s.Merge(head1, head2));
s.PrintList(s.ReverseList(head2));
return 0;
}