迅雷2014校招笔试编程题——求解两个集合差集,集合是以单向链表存储

问题描述:

已知集合A和B的元素分别用不含头结点的单链表存储,函数difference()用于求解集合A与B的差集,并将结果保存在集合A的单链表中。例如,若集合A={5,10,20,15,25,30},集合B={5,15,35,25},完成计算后A={10,20,30}。
链表结点的结构类型定义如下:

  1. struct node    
  2. {    
  3.     int elem;    
  4.     node* next;    
  5. };    
请完成函数void difference(node** LA , node* LB)

分析:这道题是以程序填空的形式出现。考点是:1链表的建立,链表的遍历、删除。2思路逻辑分析;

// DifferenceBetweenTwoSETs.cpp : 定义控制台应用程序的入口点。
/*
	@mishidemudong
	@2015-5-26

*/
//

#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node
{
	int elem;
	node* next;
};

void printList(node * Node)
{
	while (Node != NULL)
	{
		printf("%d ", Node->elem);
		Node = Node->next;
	}
}

void DestroyList(node *L)
{
	node *p, *q;
	p = q = L;
	while (p != NULL) {
		q = q->next;
		free(p);
		p = q;
	}
}

void difference(node **LA, node *LB)
{
	node *pa, *pb, *pre, *q;
	pre = NULL;
	pa = *LA;
	while (pa)
	{
		pb = LB;
		while (pb&&pb->elem!=pa->elem)
		{
			pb = pb->next;
		}
		if (pb)
		{
			if (!pre)
				*LA = pa->next;
			else
			pre->next = pa->next;
			q = pa;
			pa = pa->next;
			free(q);
		}
		else
		{
			pre = pa;
			pa = pa->next;
		}
	}
}

void CreateList(node* &L, int *Number,int length)
{
	L = new node;
	L->elem = Number[0];
	L->next = NULL;
	node *p=L;<span style="white-space:pre">	</span>//注意*p=L;
<span style="white-space:pre">					</span>
	for (int i = 1; i < length; i++)
	{
		node *newNode = (node *)malloc(sizeof(node));<span style="white-space:pre">	</span>//分配新的结点
		newNode->elem = Number[i];
		newNode->next = NULL;<span style="white-space:pre">			</span>
		p->next = newNode;<span style="white-space:pre">				</span>//尾插法,链接到链表尾部。
		p = newNode;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int A[6] = { 5, 10, 20, 15, 25, 30 };
	int B[4] = { 5, 15, 35, 25 }; 
	node *LA = NULL;
	node *LB=NULL;

	CreateList(LA, A,6);
	CreateList(LB, B, 4);
	printList(LA);
	cout << endl;
	printList(LB);
	cout << endl;
	difference(&LA, LB);
	printList(LA);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值