2-12. 两个有序链表序列的交集

最基本的一种思路,很明显是使用链表。

Node* create()创建两个空链表,find_iter是在两个链表中查找相同的元素,并直接显示出来

一个很明显的问题是算法复杂度是O(N^2)的,从submit后最后一个测试点TLE。

#include 
   
   
    
    
#include 
    
    
     
     

#define LEN sizeof(struct node)

typedef struct node{
	int s;
	struct node* next;
}Node;

Node* create()
{
	Node *p1,*p2,*pHead;
	pHead = NULL;
	p1 = p2 = (Node *)malloc(LEN);
	scanf("%d",&(p1->s));
	while((p1->s)!=-1){
		if(pHead == NULL)
			pHead = p1;
		else
			p2->next = p1;
		p2 = p1;
		p1 = (Node *)malloc(LEN);
		scanf("%d",&(p1->s));
	}
	p1->next = NULL;
	if(pHead==NULL)
	return p1;
	else
	return pHead;
	
}

//Do not need to save the intersection into a new pointer
void find_inter(Node *pHead1, Node *pHead2)
{
	int a=0;
	if(pHead1->next == NULL|pHead2->next == NULL){
		printf("NULL");
		return;
	}
	for(Node *p1 = pHead1; p1!= NULL; p1 = p1->next)
		for(Node *p2 = pHead2; p2!= NULL; p2 = p2->next)
			if(p1->s == p2->s)
			{
			if(a==0)
			printf("%d",p1->s);
			else
			printf(" %d",p1->s);
			++a;	}
	if(!a)
	printf("NULL");	

}

int main()
{
	Node *p1,*p2;
	p1=create();
	p2=create();
	find_inter(p1,p2);
}

    
    
   
   


之前的思路没有用到链表是有序的条件,将程序稍加修改,时间复杂度变为O(n+m)

#include 
   
   
    
    
#include 
    
    
     
     

#define LEN sizeof(struct node)

typedef struct node{
	int s;
	struct node *next;
}Node;

Node* create()
{
	Node *p1, *p2, *pHead;
	pHead = NULL;
	p1 = p2 = (Node *)malloc(LEN);
	scanf("%d",&(p1->s));
	while(p1->s != -1){
		if(pHead == NULL)
			pHead = p1;
		else
			p2->next = p1;
		p2 = p1;
		p1 = (Node *)malloc(LEN);
		scanf("%d", &(p1->s));
	}
	p1->next = NULL;
	if(pHead == NULL)
		return p1;
	else 
		return pHead;
}

void find_inter(Node *pHead1, Node *pHead2)
{
	int a = 0;
	Node *p1,*p2;
	if(pHead1->next == NULL | pHead2->next == NULL)
		{printf("NULL");
		return;
		}
	for(p1 = pHead1,p2 = pHead2; p1!= NULL&& p2!= NULL;){
		if(p1->s < p2->s)
			p1 = p1->next;
		else if(p1->s > p2->s)
			p2 = p2->next;
		else{
		if(!a)
			printf("%d",p1->s);
		else
			printf(" %d",p1->s);
		p1 = p1->next;
		p2 = p2->next;
		++a;
		}
	}
	if(!a)
	printf("NULL");
}

int main(){
	Node *pp1,*pp2;
	pp1 = create();
	pp2 = create();
	find_inter(pp1,pp2);
}

    
    
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值