输入俩个递增排序的链表,合并这俩个链表并使新链表中的节点仍然是按照递增排序的
#include <stdio.h>
#include <iostream>
using namespace std;
struct ListNode
{
int _value;
struct ListNode* next;
};
ListNode* createList()
{
ListNode* head = new ListNode;
head->next = NULL;
return head;
}
void insert(ListNode* head,int value)
{
ListNode* cur = new ListNode;
cur->_value = value;
cur->next = head->next;
head->next = cur;
}
//正常的遍历链表 头结点的垃圾值会越过
void TraversalList(ListNode* head)
{
if (head == NULL)
return;
ListNode* tmp = head->next; //越过垃圾值
while (tmp!=NULL)
{
cout << tmp->_value << endl;
tmp = tmp->next;
}
}
//合并链表 迭代方式
ListNode* ListMerge_diedai(ListNode* head1, ListNode* head2)
{
ListNode* mergeHead = createList(); //创建空链表
ListNode* tmp = mergeHead;
ListNode* pHead1 = head1;
ListNode* pHead2 = head2;
if (pHead1->next == NULL)
return pHead2;
else if (pHead2->next == NULL)
return pHead1;
pHead1 = head1->next;
pHead2 = head2->next;
while (pHead1 != NULL&&pHead2 != NULL) //俩者都不是空节点的情况下
{
if (pHead1->_value < pHead2->_value)
{
tmp->next = pHead1; //小的赋值
pHead1 = pHead1->next;
tmp = tmp->next;
}
else
{
tmp->next = pHead2;
pHead2 = pHead2->next;
tmp = tmp->next;
}
if (pHead1 == NULL)
{
tmp->next = pHead2;
return mergeHead;
}
else if (pHead2 == NULL)
{
tmp->next = pHead1;
return mergeHead;
}
}
}
//合并列表 递归方法
ListNode* ListMerge_digui(ListNode* head1, ListNode* head2)
{
if (head1 == NULL)
return head2;
else if (head2 == NULL)
return head1;
ListNode* mergeHead = NULL;
if (head1->_value < head2->_value)
{
mergeHead = head1;
mergeHead->next = ListMerge_digui(head1->next, head2);
}
else
{
mergeHead = head2;
mergeHead->next = ListMerge_digui(head1, head2->next);
}
return mergeHead;
}
//递归合并后的遍历方法
void TraversalList_digui(ListNode* head)
{
ListNode* tmp = head;
if (tmp == NULL)
return;
while (tmp != NULL)
{
cout << tmp->_value << endl;
tmp = tmp->next;
}
}
int main(int argc,char *argv[])
{
ListNode* head1 = createList();
ListNode* head2 = createList();
insert(head1, 7);
insert(head1, 6);
insert(head1, 3);
insert(head1, 1);
insert(head2, 8);
insert(head2, 6);
insert(head2, 3);
insert(head2, 2);
TraversalList(head1);
cout << "------------------" << endl;
TraversalList(head2);
cout << "------------------" << endl;
//迭代测试
//ListNode* head_AfterMerge = ListMerge_diedai(head1, head2);
//TraversalList(head_AfterMerge);
//递归测试
ListNode* head_AfterMerge = ListMerge_digui(head1->next, head2->next); //参数需要越过头结点垃圾值
TraversalList_digui(head_AfterMerge);
cout << "------------------" << endl;
return 0;
}