1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
#include <iostream>
using namespace std ;
struct Node {
Node * link ;
int data ;
};
void Add(Node*& n, int d) ;
Node* CopySingletonsGatherDups(Node*&);
ostream& operator<<(ostream&, Node*);
int main()
{
int values[] = { 2, 5, 4, 4, 0, 0, 4, 5, 1, 2, 1, 2, 1, 3, 0, 4 } ;
Node * l1 = 0 ;
for ( unsigned i=0; i<sizeof(values)/sizeof(values[0]) ; ++i )
Add(l1, values[i]) ;
cout << "List 1: " << l1 << '\n' ;
Node* l2 = CopySingletonsGatherDups(l1) ;
cout << "List 1: " << l1 ;
cout << "List 2: " << l2 ;
// free memory here.
}
ostream& operator<<(ostream& os, Node* list)
{
if ( list == 0 )
{
os << "{empty}\n" ;
return os ;
}
os << '{' ;
while (list != nullptr )
{
os << ' ' << list->data ;
list = list->link ;
}
os << " }\n" ;
return os ;
}
void Add( Node *& n, int d )
{
Node* newNode = new Node ;
newNode->data = d ;
newNode->link = n ;
n = newNode ;
}
Node* CopySingletonsGatherDups (Node*& list)
{
if(list == 0 || list->link == 0)
return 0 ;
Node* destList = 0 ;
Node* destTail = 0 ;
Node* workingHead = list ;
Node* workingNode = list->link ;
Node* prevNode = list ;
while(workingHead != 0)
{
bool isUnique = true;
// cout << "List 1: " << list ;
// cout << "List 2: " << destList ;
while(workingNode != 0)
{
if( workingNode->data == workingHead->data)
{
isUnique = false;
// remove from list
prevNode->link = workingNode->link ;
workingNode->link = 0 ;
// add to destination list
if ( destList==0 )
destList = destTail = workingNode ;
else
{
destTail->link = workingNode ;
destTail = workingNode ;
}
workingNode = prevNode->link ;
}
else
{
prevNode = workingNode ;
workingNode = workingNode->link ;
}
}
if ( isUnique )
{ // add a copy to the destination list
Node * newNode = new Node ;
newNode->data = workingHead-> data;
newNode->link = 0 ;
if ( destList == 0 )
destList = destTail = newNode ;
else
{
destTail->link = newNode ;
destTail = newNode ;
}
}
if ( workingHead->link == 0 )
return destList ;
workingHead = workingHead->link ;
prevNode = workingHead ;
workingNode = workingHead->link ;
}
}
|