编写一个能将链表合成与排序的小程序。
编写程序,把两个有序排列的单向整数链表合并成一个有序排列的的整数链表。
具体实现如下:
从小到大依次输入两列整数,以-1表示结尾,然后根据这两列整数构造两个单向链表,按整数大大小关系把这两个链表合并成一个有序单向链表,最后从头到尾遍历输出这个链表的数据域(用一个空格隔开)。
效果如下:
输入:
1 4 7 8 14 23 -1
2 5 6 11 37 -1
输出:
1 2 4 5 6 7 8 11 14 23 37
//不使用链表
#include <iostream>
using namespace std;
int main()
{
int a[100];
int n,i,t=0;
for(i=0;;i++)
{
cin>>a[i];
if(a[i]==-1)
{
break;
}
}
for(t=i;;t++)
{
cin>>a[t];
if(a[t]==-1)
{
break;
}
}
for(int j=0;j<t-1;j++)
{
for(int m=0;m<t-j-1;m++)
{
if(a[m]>a[m+1])
{
n=a[m];
a[m]=a[m+1];
a[m+1]=n;
}
}
}
for(int h=0;h<t;h++)
{
if(a[h]==-1)
{
continue;
}
else
{
cout<<a[h]<<" ";
}
}
}
或
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node *creatList();
void sortList(node *);
node *merage(node *, node *);
void displayList(node *);
void clearList(node *);
int main()
{
node *head1 = creatList();
node *head2 = creatList();
sortList(head1);
sortList(head2);
node *newHead = merage(head1, head2);
displayList(newHead);
clearList(newHead);
return 0;
}
node *creatList()
{
node *head = NULL;
int num;
cin >> num;
while (num != -1)
{
node *tmp = new node;
if (tmp == NULL)
{
return head;
}
tmp->data = num;
tmp->next = head;
head = tmp;
cin >> num;
}
return head;
}
void sortList(node *head)
{
if (head == NULL)
return;
node *tmp = head;
while (tmp->next != NULL)
{
node *min = tmp;
node *tmp1 = tmp->next;
while (tmp1 != NULL)
{
if (min->data > tmp1->data)
{
min = tmp1;
}
tmp1 = tmp1->next;
}
if (min != tmp)
{
int data = tmp->data;
tmp->data = min->data;
min->data = data;
}
tmp = tmp->next;
}
}
node *merage(node *head1, node *head2)
{
node *tmp1 = head1;
node *tmp2 = head2;
node *newHead = NULL;
node *newTail = NULL;
while (tmp1 != NULL || tmp2 != NULL)
{
if (tmp1 != NULL && (tmp2 == NULL || tmp1->data < tmp2->data))
{
if (newHead == NULL)
{
newHead = tmp1;
}
else
{
newTail->next = tmp1;
}
newTail = tmp1;
tmp1 = tmp1 ->next;
}
else
{
if (newHead == NULL)
{
newHead = tmp2;
}
else
{
newTail->next = tmp2;
}
newTail = tmp2;
tmp2 = tmp2 ->next;
}
}
return newHead;
}
void displayList(node *head)
{
node *tmp = head;
while (tmp != NULL)
{
cout <<tmp->data<<" ";
tmp = tmp->next;
}
}
void clearList(node *head)
{
node *tmp = head;
while (tmp != NULL)
{
head = head->next;
delete tmp;
tmp = head;
}
}