实验11-2-5 链表拼接 (20 分)
1. 题目摘自
https://pintia.cn/problem-sets/13/problems/605
2. 题目内容
本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:
struct ListNode {
int data;
struct ListNode *next;
};
函数接口定义:
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
其中list1和list2是用户传入的两个按data升序链接的链表的头指针;函数mergelists将两个链表合并成一个按data升序链接的链表,并返回结果链表的头指针。
输入样例:
1 3 5 7 -1
2 4 6 -1
输出样例:
1 2 3 4 5 6 7
3. 源码参考
#include <iostream>
#include <stdlib.h>
using namespace std;
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode *list1, *list2;
list1 = createlist();
list2 = createlist();
list1 = mergelists(list1, list2);
printlist(list1);
return 0;
}
struct ListNode *createlist()
{
struct ListNode *p, *h, *t;
int n;
h = t = NULL;
cin >> n;
while(n != -1)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->data = n;
p->next = NULL;
if(h == NULL)
{
h = p;
}
else
{
t->next = p;
}
t = p;
cin >> n;
}
return h;
}
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2)
{
struct ListNode *p1,*p2,*h,*t,*p;
int a[100];
int n;
int i,j,te;
if((list1==NULL)&&(list2==NULL))
{
return NULL;
}
n=0;
p1=list1;
while(p1)
{
a[n++]=p1->data;
p1=p1->next;
}
p2=list2;
while(p2)
{
a[n++]=p2->data;
p2=p2->next;
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
te=a[i];
a[i]=a[j];
a[j]=te;
}
}
}
h=t=NULL;
for(i=0;i<n;i++)
{
p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->data=a[i];
p->next=NULL;
if(h==NULL)
{
h=p;
}
else
{
t->next=p;
}
t=p;
}
return h;
}
网友评论