删除两个双向链表中相同元素的所有结点
1 #include <iostream> 2 #include <ctime> 3 using namespace std; 4 #define TAG 0xFFFFFFFF 5 6 typedef struct _Node 7 { 8 int data; 9 struct _Node *front, *next; 10 }Node; 11 12 class DuLinkList 13 { 14 public: 15 DuLinkList() 16 { 17 head = new Node; 18 head->data = TAG; 19 head->front = head; 20 head->next = head; 21 } 22 ~DuLinkList() 23 { 24 Node *p = head; 25 Node *q = head->next; 26 while(q->data != TAG) 27 { 28 p->next = q->next; 29 q->next->front = p; 30 delete q; 31 q = p->next; 32 } 33 34 delete p; 35 } 36 37 void InsertNode(int data); 38 friend intDeleteSameNodes(DuLinkList *pHeadA, DuLinkList *pHeadB); 39 void Print(); 40 41 private: 42 Node *head; 43 }; 44 45 void DuLinkList::InsertNode(int data) 46 { 47 Node *temp = new Node; 48 temp->data = data; 49 50 temp->next = head->next; 51 head->next->front = temp; 52 53 temp->front = head; 54 head->next = temp; 55 } 56 57 void DuLinkList::Print() 58 { 59 for (Node *p=head->next; p->data != TAG; p=p->next) 60 { 61 cout<<p->data<<endl; 62 } 63 cout<<"-------"<<endl; 64 } 65 66 int DeleteSameNodes(DuLinkList *pHeadA,DuLinkList *pHeadB) 67 { 68 Node *pA ; 69 Node *pB ; 70 71 bool deleteFlag = false; 72 for (pA=pHeadA->head->next;pA->data != TAG; NULL) 73 { 74 for (pB=pHeadB->head->next;pB->data != TAG; NULL ) 75 { 76 Node *q = pB->next;//先把下一个节点保存下来 77 if (pA->data == pB->data) 78 { 79 //delete the node from PB 80 pB->next->front =pB->front; 81 pB->front->next =pB->next; 82 delete pB; 83 84 deleteFlag = true; 85 } 86 pB = q; 87 } 88 89 if ( deleteFlag == true)//有删除 90 { 91 //删除A中跟该节点相同的其他节点 92 //e.g: 1-2-2-1-1 93 for (Node *p = pA->next;p->data != TAG;) 94 { 95 Node *tempSave =p->next;// 96 if (p->data ==pA->data) 97 { 98 p->next->front =p->front; 99 p->front->next =p->next; 100 delete p; 101 } 102 p = tempSave;//后移一个节点 103 } 104 Node *tempNextNode = pA->next; 105 106 pA->next->front = pA->front; 107 pA->front->next = pA->next; 108 delete pA;//删除节点自身 109 pA = tempNextNode;//恢复PA身份 110 deleteFlag = false;//标志还原 111 } 112 else//没有删除 113 pA = pA->next; 114 } 115 return 0; 116 } 117 118 int main() 119 { 120 DuLinkList *pHeadA = new DuLinkList; 121 DuLinkList *pHeadB = new DuLinkList; 122 int data=0; 123 srand(time(0)); 124 125 for (int i=0;i<5;i++) 126 { 127 data = rand() % 5; 128 //data = i+2; 129 pHeadA->InsertNode(data); 130 } 131 132 for (i=0;i<4;i++) 133 { 134 data = rand() % 6; 135 //data = 2; 136 pHeadB->InsertNode(data); 137 } 138 139 pHeadA->Print(); 140 cout<<endl; 141 pHeadB->Print(); 142 143 144 cout<<"after delete:"<<endl; 145 DeleteSameNodes(pHeadA,pHeadB); 146 147 pHeadA->Print(); 148 cout<<endl; 149 pHeadB->Print(); 150 151 delete pHeadA; 152 delete pHeadB; 153 return 0; 154 }