public void setIntersection(LinkList list1, LinkList list2) {
LinkList list4 = new LinkList();
Node a = list1.head;
Node b = list2.head;
while (a != null && b != null) {
if (a.value < b.value) {
a = a.next;
} else if (a.value > b.value) {
b = b.next;
} else if (a.value == b.value){
list4.insert(a.value);
a = a.next;
b = b.next;
}
}
list4.printList();
}
我想找出列表1和列表2中出现的公共值,并保存List4中的条目。虽然这看起来很简单,但我仍觉得我的代码太长了,想知道是否有更有效的方法来解决这个问题?
答案 0 :(得分:1)
struct LinkList
{
int data;
struct LinkList *next;
}*list1,*list2,*list4;
public void setIntersection(LinkList *list1, LinkList *list2)
{
LinkList *temp, *temp1, *temp2, *node;
for(temp1 = list1;temp1!=null;temp1=temp1->next)
{
enter code here for(temp2 = list2;temp2!=null;temp2=temp2->next)
{
if(temp1->data == temp2->data)
{
node = (struct LinkList *)malloc(sizeof(struct LinkList));
node->next = null;
if(list4==null)
{
list4 = node;
}
else
{
for(temp = list4;temp->next!=NULL;temp=temp->next);
temp->next = node;
}
}
}
}
}