题目描述:输入两个递增排序的链表,合并这两个链表,并使新链表中的结点仍然按照递增排序。
思路分析:
代码:
#include<iostream>
#include<stack>
using namespace std;
//不带头结点的单向链表
struct Node
{
int data;
Node *next;
};
bool Insert_tail(Node **list,int value)//尾插
{
Node *node = new Node;
node -> data = value;
node ->next = NULL;
if(*list == NULL)
{
*list = node;
return true;
}
Node *p = *list;
for(;p->next !=NULL;p=p->next );
p->next = node;
return true;
}
Node* Merge(Node *list1,Node *list2)
{
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
Node *newnode = NULL;
if(list1->data < list2->data)
{
newnode = list1;
newnode->next = Merge(list1->next,list2);
}
else
{
newnode = list2;
newnode->next = Merge(list1,list2->next );
}
return newnode;
}
void clear(Node **list)//清除
{
Node *p = *list;
for(;p!=NULL;p=p->next )
{
Node *q = p -> next;
p->next = q->next;
delete q;
}
delete p;
}
void Show(Node *list)//打印函数
{
if(list == NULL)
return;
Node *p = list;
for(;p != NULL;p = p->next)
{
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
Node *head1 = NULL;
Node *head2 = NULL;
int arr[] = {1,3,4,6,10};
int brr[] = {2,5,7,8,18};
int lenarr = sizeof(arr)/sizeof(arr[0]);
int lenbrr = sizeof(brr)/sizeof(brr[0]);
for(int i=0;i<lenarr;++i)
{
Insert_tail(&head1,arr[i]); //尾插
}
for(int i=0;i<lenbrr;++i)
{
Insert_tail(&head2,brr[i]); //尾插
}
Show(head1);
Show(head2);
Node *newhead = Merge(head1,head2);
Show(newhead);
clear(&newhead);
return 0;
}