- 9月9日,迅雷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;
- };
点评:参考答案或更多题目请参见:http://blog.csdn.net/hackbuteer1/article/details/11482103。
#include<iostream>
using namespace std;
struct node
{
int elem;
node* next;
};
/*void difference(node* LA , node* LB)
{
node *tempA, *tempB, *preA, *preB;
tempA = LA;
tempB = LB;
while(LA->elem == LB->elem && LA != NULL && LB != NULL)
{
tempA = LA;
LA = LA->next;
LB = LB->next;
delete tempA;
}
preA = LA;
preB = LB;
if(LA != NULL)
tempA = LA->next;
if(LB != NULL)
tempB = LB->next;
while(tempA != NULL && tempB != NULL)
{
if(tempA->elem > tempB->elem)
{
tempB = tempB->next;
}
else if(tempA->elem < tempB->elem)
{
tempA = tempA->next;
}
}
};*/
void difference(node** LA , node* LB)
{
node *pa, *pb, *pre, *q;
pre = NULL;
pa = *LA;
while(pa)
{
pb = LB;
while(pb->elem != pa->elem)
{
pb = pb->next;
if(pb == NULL)//此处不能省略,若pb为空时,
break;
}
if(pb == NULL)//LB链不含LA当前节点
{
if(pre == NULL)//可修改为:if(!pre)
{
*LA = pa;
pre = pa;
pa = pa->next;
}
else
{
pre = pa;
pa = pa->next;
}
}
else//LB链含LA当前节点
{
if(pre == NULL)
{
q = pa;
pa = pa->next;
delete q;
*LA = pa;
}
else
{
q = pa;
pa = pa->next;
pre->next = pa;
delete q;
}
}
}
}
/*
void difference(node** LA , node* LB)
{
node *pa , *pb , *pre , *q;
pre = NULL;
pa = *LA; //1
while(pa)
{
pb = LB;
while(pb && pa->elem != pb->elem) //2
pb = pb->next;
if(pb != NULL) //3
{
if(!pre)
*LA = pa->next; //4
else
pre->next = pa->next; //5
q = pa;
pa = pa->next;
free(q);
}
else
{
pre = pa; //6
pa = pa->next;
}
}
} */
int main()
{
int A[6] = {5,10,20,15,25,30};
int B[4] = {5,15,35,25};
node* LA = new node;
LA = NULL;
node* LB = new node;
LB = NULL;
for(int i=5;i>=0;i--)
{
node *temp = new node;
temp->elem = A[i];
temp->next = LA;
LA = temp;
}
for(int i=3;i>=0;i--)
{
node *temp = new node;
temp->elem = B[i];
temp->next = LB;
LB = temp;
}
difference(&LA, LB);
while(LA != NULL)
{
cout<<LA->elem<<" ";
LA = LA->next;
}
return 0;
}