首页 > 试题广场 >

有双向循环链表结点定义为: struct node {

[问答题]

有双向循环链表结点定义为:

struct node
{ 
   int data;
   struct node *front,*next;
};

有两个双向循环链表A,B,知道其头指针为:pHeadA,pHeadB,请写一函数将两链表中data值相同的结点删除。

#include <iostream>
#include <map>
using namespace std;

struct Node
{
    int data;
    Node *front, *next;
};

void DeleteCommonNode(Node *&pHeadA, Node*pHeadB)
{
    if(pHeadA == NULL || pHeadB == NULL)
        return ;
        
    map<int,Node *> hmap;
    Node *tmp = pHeadA; 
    while(tmp)
    {
        hmap[tmp->data] = tmp;
        tmp = tmp->next;
    }
    Node *tmpb = pHeadB;
    while(tmpb)
    {
        if(hmap[tmpb->data] != NULL)
        {
            //存在相同data,从A和B中删除
            if(tmpb == pHeadB)
            {
                pHeadB = pHeadB->next;
                pHeadB->front = NULL; 
            }
            else
            {
                tmpb->front->next = tmpb->next;
                tmpb->next->front = tmpb->front;
            } 
            delete tmpb;
            
            Node *tmpa = hmap[tmpb->data];
            hmap.erase(tmpa->data);
            if(tmpa == pHeadA)
            {
                pHeadA = pHeadA->next;
                pHeadA->front = NULL; 
            }
            else
            {
                tmpa->front->next = tmpa->next;
                tmpa->next->front = tmpa->front;
            }
            delete tmpa;
            
             
        }
    }
    
    
}
int main(void)
{
    return 0;
}
网上抄的代码https://www.cnblogs.com/mickole/articles/3616905.html
发表于 2019-09-03 21:57:52 回复(0)
更多回答
用hashset 可以删除重复
发表于 2015-10-28 00:26:22 回复(0)

因为双向直接从头和尾进行比较

发表于 2015-05-04 11:08:44 回复(0)
先对两个链表排序,然后遍历删除相同的值。
发表于 2015-05-04 06:49:09 回复(0)