linked list delete dups

I have a problem that i need to solve. For example this is the list
2 - 7 - 11 - 2 - 7 - 2. there are 2 duplicates of 2's. What i need to write a code for is that i need to delete the last copy of 2 which is the last element in this case.

and also how would i go about deleting the SECOND LAST COPY IF THERE ARE 2 OR MORE THAN 3 DUPLICATED COPIES for example
5 7 11 5 7 5 11 7

in this case i would have to delete the middle 7.

Any help is appreciated. I will post what i have so far. My code deletes all duplicates which is not what i want

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
 oid List::DeleteLastDupicate(int &x, bool & success)
{
	 Node *ptr1, *ptr2, *dup;
	ptr1 = head;

	
	while (ptr1 != NULL && ptr1->next != NULL)
	{
		ptr2 = ptr1;

		
		while (ptr2->next != NULL)
		{
			
			if (ptr1->data == ptr2->next->data)
			{
				
				dup = ptr2->next;
				ptr2->next = ptr2->next->next;
				delete dup;
			}
			else 
			{
				ptr2 = ptr2->next;
			}
		}
		ptr1 = ptr1->next;
	}
}
Anyone?
First, your list could have a convenience helper function:
1
2
void List::demolish( Node * n );
// deletes n, if it is in this list 


Second, you could have a:
std::vector<Node*> List::nodesThatContainValue( typeof(Node::data) value );

Now,
1
2
3
4
5
6
List foo;
// fill list
auto sevens = foo.nodesThatContainValue( 7 );
if ( 2 < sevens.size() ) {
  foo.demolish( sevens[ sevens.size() / ] );
}
Last edited on
Topic archived. No new replies allowed.