本文主要是介绍迅雷2014校招笔试编程题——求解两个集合差集,集合是以单向链表存储,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
已知集合A和B的元素分别用不含头结点的单链表存储,函数difference()用于求解集合A与B的差集,并将结果保存在集合A的单链表中。例如,若集合A={5,10,20,15,25,30},集合B={5,15,35,25},完成计算后A={10,20,30}。
链表结点的结构类型定义如下:
- struct node
- {
- int elem;
- node* next;
- };
分析:这道题是以程序填空的形式出现。考点是: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;elsepre->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;
}
这篇关于迅雷2014校招笔试编程题——求解两个集合差集,集合是以单向链表存储的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!