思路:一个指针指向第一个链表,一个指针指向第二个链表,若俩个指针指向的节点的值相等,则用L指向这个节点,并且俩个指针都后移;否则指向节点值小的指针后移
#include <iostream>
using namespace std;
typedef struct LNode * List;
struct LNode
{
int data;
struct LNode * next;
};
List ReadList();
List Intersection(List L1, List L2);
void PrintList(List L);
int main()
{
List L1, L2, L;
L1 = ReadList();
L2 = ReadList();
L = Intersection(L1, L2);
PrintList(L);
return 0;
}
List ReadList()
{
List L, p, head;
L = (List)malloc(sizeof(struct LNode));
L->next = NULL;//L是空头节点
head = L;
int e;
while(~scanf("%d", &e)){
if(e == -1)
break;
p = (List)malloc(sizeof(struct LNode));
p->next = NULL;
p->data = e;
L->next = p;
L = L->next;
}
L = head->next;
free(head);
return L;
}
void PrintList(List L)
{
if(L == NULL)
printf("NULL\n");
else{
printf("%d", L->data);
L=L->next;
while(L){
printf(" %d", L->data);
L = L->next;
}
printf("\n");
return;
}
}
List Intersection(List L1, List L2)
{
List p1, p2, L, tmp, head;
p1 = L1, p2 = L2;
L = (List)malloc(sizeof(struct LNode));
L->next = NULL;
head = L;
while(p1 && p2){
if(p1->data == p2->data)
{
L->next = p1;
p1 = p1->next;
p2 = p2->next;
L = L->next;
}
else if(p1->data < p2->data){
p1 = p1->next;
}
else
p2 = p2->next;
}
L = head->next;
free(head);
return L;
}