1
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();
}

我想找出出现在 List 1 和 List 2 中的共同值,并将条目保存在 List4 中。虽然这看起来很简单,但我仍然觉得我的代码太长了,想知道是否有更有效的方法来解决这个问题?

4

1 回答 1

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;
                  }
              }
         }
    }
}
于 2012-02-14T10:13:45.700 回答