#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node* next;
Node(
int
x)
{
this
->data = x;
this
->next = NULL;
}
};
Node* reverseList(Node* head)
{
Node *prev = NULL, *nextNode = NULL;
while
(head != NULL) {
nextNode = head->next;
head->next = prev;
prev = head;
head = nextNode;
}
return
prev;
}
Node* Remove_Dup_Keep_Last_Occurrence(
Node* head)
{
Node* dummy =
new
Node(-1);
dummy->next = head;
dummy->next = reverseList(dummy->next);
unordered_set<
int
> visited;
Node *currNode = dummy, *nextNode;
while
(currNode != NULL
&& currNode->next != NULL) {
nextNode = currNode->next;
if
(visited.count(nextNode->data) != 0) {
Node* duplicate = nextNode;
currNode->next = nextNode->next;
delete
duplicate;
}
else
{
visited.insert(nextNode->data);
currNode = nextNode;
}
}
dummy->next = reverseList(dummy->next);
return
dummy->next;
}
void
print_Linked_List(Node* head)
{
Node* curr = head;
while
(curr != NULL) {
cout << curr->data <<
' '
;
curr = curr->next;
}
}
int
main()
{
Node* head =
new
Node(3);
head->next =
new
Node(2);
head->next->next =
new
Node(3);
head->next->next->next =
new
Node(1);
head->next->next->next->next =
new
Node(5);
head->next->next->next->next->next =
new
Node(1);
head->next->next->next->next->next->next =
new
Node(6);
head = Remove_Dup_Keep_Last_Occurrence(head);
print_Linked_List(head);
return
0;
}