求两个链表的交集
/* 2.12 假设有两个按元素值递增有序排列的有序表A和B,均以单链表作存储结构。*请编写算法利用A表和B表中原有的结点将A表和B表归并成一个按元素值非递增有序排列的有序表C。
*( 例如: A=(1,2.3,4.6),B=(2,3,5,7,9),则 C=(9,7,6,5.4,3,3,2,2,1) )
*/
# include <stdio.h>
# include <malloc.h>
typedef struct node
{
int data;
node *pNext;
}NODE, *PNODE;
PNODE create(int array[])//创建链表
{
PNODE pHead, pTail, pNew;
pHead = (PNODE)malloc(sizeof(NODE));
pTail = pHead;
pTail->pNext = NULL;
for (int i=0; i<5; i++)
{
pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = array[i];
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traverse(PNODE pHead)//遍历链表
{
PNODE pTemp = pHead->pNext;
while (NULL != pTemp)
{
printf("%d ", pTemp->data);
pTemp = pTemp->pNext;
}
printf("\n");
}
PNODE coalition(PNODE A, PNODE B)// A 和 B 的交集
{
PNODE pHead, pTail, pNew;
PNODE pTemp1 = A->pNext;
PNODE pTemp2 = B->pNext;
PNODE p = NULL;
PNODE q = pTemp2;
pHead = (PNODE)malloc(sizeof(NODE));
pTail = pHead;
pTail->pNext = NULL;
while (NULL != pTemp1)
{
printf("%d-----1--------------\n", pTemp1->data);
p = pTemp1->pNext;
//保存数据
pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = pTemp1->data;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
while (NULL != pTemp2)
{
printf("%d-------2--------------\n", pTemp2->data);
if (pTemp2->data >= pTemp1->data && pTemp2->data <= p->data)
{
//保存到c中的
pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = pTemp2->data;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
pTemp2 = pTemp2->pNext;
}
pTemp2 = q = q->pNext;
pTemp1 = pTemp1->pNext;
}
return pHead;
}
PNODE reverse_copy_list(PNODE &pHead) //逆置链表
{
PNODE p, q;
p = pHead;
pHead = NULL;
while (NULL != p)
{
q = p;
p = p->pNext;
q->pNext = pHead;
pHead = q;
}
return pHead;
}
int main()
{
int A[5] = {1, 2, 3, 5, 6}, B[5] = {2, 5, 7, 8, 9};
PNODE pHead = NULL, pHeadA = NULL, pHeadB = NULL;
pHeadA = create(A);
pHeadB = create(B);
pHead = coalition(pHeadA, pHeadB);
pHead = reverse_copy_list(pHead);//逆序
printf("改变后的链表 : \n");
traverse(pHead);
return 0;
}
每次运行到coalition();就会终止, 是为什么,怎样修改呀?