数据结构入门系列——用链表解决实际问题(2)

交集

lnode *Jiaoji(lnode *a, lnode *b)
{
     
	lnode *c = InitList(); lnode *pa = a->next, *pb = b->next,*pc,*pre=c;
	while (pa)
	{
     
		pb = b->next;                    //①容易忘记
		while (pb)
		{
     
			if (pa->data == pb->data)
			{
     
				pc = new lnode;
				pc->data = pa->data;   
				pre->next = pc;         //②一定是创建链表的语法,这两句不能少。
				pre = pc;
				pc = pc->next;
			}
			pb = pb->next;
		}
		pa = pa->next;
	}
	pre->next = NULL;
	return c;
}

并集

lnode *merge(lnode *a, lnode *b)
{
     
	lnode *c = new lnode;
	lnode *pa = a->next, *pb = b->next, *pc, *pre = c;
	while (pa)
	{
     
		pc = new lnode;
		pc->data = pa->data;
		pre->next = pc;
		pre = pc;
		pa = pa->next;
	}
	while (pb)
	{
     
		int m = 0;
		pa = a->next;
		while (pa)
		{
     
			if (pa->data == pb->data)
				m++;
			pa = pa->next;
		}
		if (m == 0)
		{
     
			pc = new lnode;
			pc->data = pb->data;
			pre->next = pc;
			pre = pc;
		}
		pb = pb->next;
	}
	pre->next = NULL;
	return c;
}

奇偶分类

将一个链表中的奇数放在前面,偶数放在后面。

void OddEven(lnode *l)
{
     
	/*这个很重要,不是p=l->next;因为第一个元素不需要移动。*/
	lnode *p = l->next->next;
	lnode *pre =l->next;
	while (p)
	{
     
		if (p->data % 2 != 0)
		{
     
			pre->next = p->next;
			p->next = l->next;
			l->next = p;
			p = pre->next;
		}
		else
		{
     
			pre = p; p = p->next;
		}
	}
}

你可能感兴趣的:(数据结构)