33,311
社区成员
发帖
与我相关
我的任务
分享
node* merge(node *p1, node *p2)
{
if( p1 == NULL && p2 == NULL)
{
cout<<"the node is empty"<<endl;
return NULL;
}
else if( p1 == NULL ) return p2;
else if( p2 == NULL ) return p1;
//先从p2中删除p1已有的结点,然后将p2整体连接在p1后面
node *p2Head = new node(0, p2); //因为不知道你的结构,所以自己加一个头结点,方便下面操作
node *p2Pre = p2Head;
node *p2Cur = p2Head->next;
while(p2Cur != NULL)
{
node *p1Cur = p1;
while( p1Cur != NULL && p2Cur->value != p1Cur->value )
p1Cur = p1Cur->next;
//如果p1Cur的结果非空,意味着上面的循环是碰到了数值一致的情况
if( p1Cur != NULL )
{
//将与p1有重复的结点从p2中移除
p2Pre->next = p2Cur->next;
delete p2Cur;
}
else
p2Pre = p2Pre->next;
p2Cur = p2Pre->next;
}
//最后,将p2的结果接于p1后即可,注意移除辅助的头结点。
node *p1Rear = p1;
while( p1Rear->next != NULL ) p1Rear = p1Rear->next;
p1Rear->next = p2Head->next;
delete p2Head;
return p1;
}