您的位置:首页 > 移动开发

请修改append函数,利用这个函数实现

2012-05-21 23:44 323 查看
两个非降序链表的并集,1->2->3 和 2->3->5 并为 1->2->3->5

另外只能输出结果,不能修改两个链表的数据。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct Node
{
int num;
Node * next;
};

Node * createTail()
{
int x;
Node *head = NULL, *p = NULL, *tail = NULL;
puts("\nplease enter some digits(end of '.'):");
while( scanf("%d",&x) )
{
p = (Node *)malloc(sizeof(Node));
p->num = x;
p->next = NULL;
if( NULL == head )
{
tail = p;
head = tail;
}
else
{
tail->next = p;
tail = p;
}
}
getchar();
return head;
}

Node * CombinationNode(Node* head1, Node* head2)
{
Node *head,*tail,*p = head1,*q = head2,*s;

if( NULL == p )
return q;
if( NULL == q )
return p;

tail = p;
if( p->num > q->num)
tail = q;
head = tail;

while( NULL != p && NULL != q )
{
if(p->num <= q->num )
{
s = p;
p = p->next;
}
else
{
s = q;
q = q->next;
}
tail->next = s;
tail = s;
}

if( NULL == p ) p = q;

s = p;
tail->next = s;

return head;
}

void printHead(Node *head)
{
if( NULL == head )
return;
printf("List: ");
while(head)
{
printf("%d->",head->num);
head = head->next;
}
puts("NUL");
}

void main( void )
{
Node* head1,*head2,*head;
head1 = createTail();
printHead(head1);

head2 = createTail();
printHead(head2);

head = CombinationNode(head1,head2);
printHead(head);
}
//////////////////////////////////////////////////////////////////////////////

please enter some digits(end of '.'):
1
3
5
7
9
.
List: 1->3->5->7->9->NUL

please enter some digits(end of '.'):
2
4
5
6
7
8
9
.
List: 2->4->5->6->7->8->9->NUL
List: 1->2->3->4->5->5->6->7->7->8->9->9->NUL
Press any key to continue
//////////////////////////////////////////////////////////////////////////////
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐