#include <iostream>
using namespace std;
struct MyNode {
int val;
MyNode *next;
};
MyNode* create_link(int arr[], int num) {
MyNode *head, *p, *node;
head = NULL;
for(int i = 0; i <= num - 1; ++i) {
p = new MyNode;
p->val = arr[i];
p->next = NULL;
if(head == NULL) {
head = p;
} else {
node->next = p;
}
node = p;
}
return head;
}
MyNode* merge_link(MyNode* head1, MyNode* head2) {
if (!head1) {
return head2;
}
if (!head2) {
return head1;
}
if (head1->val < head2->val) {
head1->next = merge_link(head1->next, head2);
return head1;
} else {
head2->next = merge_link(head1, head2->next);
return head2;
}
}
MyNode* reverse_link(MyNode* head)
{
MyNode* link_head = head;
MyNode* link_tail;
MyNode* preNode = NULL;
MyNode* pNode = head;
MyNode* afterNode = head->next;
for (pNode = link_head; pNode != NULL; pNode = afterNode) {
afterNode = pNode->next;
pNode->next = preNode;
preNode = pNode;
}
link_tail = preNode;
link_head = link_tail;
return link_head;
}
void print_link(MyNode* p) {
while(p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
int main() {
int arr1[] = {1, 5, 7};
int arr2[] = {2, 4, 6};
int num1 = sizeof(arr1) / sizeof(int);
int num2 = sizeof(arr2) / sizeof(int);
MyNode *head1, *head2, *new_head, *rev_head;
head1 = create_link(arr1, num1);
head2 = create_link(arr2, num2);
print_link(head1);
print_link(head2);
cout << "merge_link: " << endl;
new_head = merge_link(head1, head2);
rev_head = reverse_link(new_head);
print_link(rev_head);
return 0;
}
运行结果
1 5 7
2 4 6
merge_link:
7 6 5 4 2 1
网友评论