7-2 两个有序链表序列的交集(简单解法,推荐)

两个有序链表序列的交集 (20分)

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:

1 2 5 -1
2 4 5 8 10 -1

输出样例:

2 5

思路:这里既然s1,s2已经为升序排列,故将两链表数进行比较,数小的进至下一节点,当两表数相同时,记录

AC代码

#include <stdio.h>
#include <stdlib.h>
struct Node 
{
    
    
 	int data;
 	struct Node *next;
};
struct Node *build();
struct Node *operate(struct Node *a,struct Node *b);
int main() 
{
    
    
 	struct Node *a,*b,*c;
 	a=build();
 	b=build();
 	c=operate(a,b);
 	if(!c)
  		printf("NULL\n");
 	while(c)
 	{
    
    
  		if(c->next==NULL)
   			printf("%d",c->data);
  		else
   			printf("%d ",c->data);
  		c=c->next;
 	} 
}
struct Node *build()
{
    
    
 	int a;
 	struct Node *head=NULL,*str=NULL;
 	scanf("%d",&a);
 	while(a!=-1)
 	{
    
    
  		struct Node *p=(struct Node*)malloc(sizeof(struct Node));
  		p->data=a;
  		p->next=NULL;
  		if(head==NULL)
   			head=p;
  		else
   			str->next=p;
  		str=p; 
  		scanf("%d",&a);
 	}
 	return head;
}
struct Node *operate(struct Node *a,struct Node *b)
{
    
    
 	struct Node *head=NULL,*str=NULL;
 	while(a&&b)
    	{
    
    
        	if((a->data)<(b->data))
           		a=a->next;
        	else if((a->data)>(b->data))
            		b=b->next;
        	else if((a->data)==(b->data))
        	{
    
    
         		if(head==NULL)
          			head=a;
         		else
          			str->next=a;
         		str=a;        
         		a=a->next;
         		b=b->next;
         		str->next=NULL;//放在这里很重要,要先将a进至下一节点,防止直接将链表a中断
  		}
 	}
 	return head;
}

猜你喜欢

转载自blog.csdn.net/weixin_45989486/article/details/106031618