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
|
#include <iostream>
#include <memory>
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {};
ListNode(int x) : val(x), next(nullptr) {};
ListNode(int x, ListNode *next) : val(x), next(next) {};
};
class Solution
{
public:
ListNode * deleteDuplicates(ListNode * head)
{
std::shared_ptr<ListNode> shared_pointer = std::make_shared<ListNode>();
// use dummy node; head and tail are initially the same but tail progresses forward
ListNode * dummy_head = shared_pointer.get();
ListNode * tail = dummy_head;
int currVal = -101;
ListNode * prev_node = dummy_head;
while(head != nullptr)
{
if(head->val == currVal)
{
prev_node->next = head->next;
tail = prev_node;
}
else
{
currVal = head->val;
prev_node = tail;
// include 'head' on this trail
tail->next = head;
tail = head;
}
head = head->next; // progress the singly-linked list forward
}
return dummy_head->next; // return the trail that 'tail' blazed for us.
};
};
void printLinkedList(ListNode * head)
{
std::cout << '[';
while(head != nullptr)
{
std::cout << head->val;
if (head->next != nullptr)
std::cout << ',';
head = head->next;
}
std::cout << ']' << '\n';
}
int main()
{
Solution solutionObj;
ListNode * head = new ListNode(1,new ListNode(2, new ListNode(3, new ListNode(3, new ListNode(4, new ListNode(4, new ListNode(5)))))));
// std::shared_ptr<ListNode> head = std::make_shared<ListNode>(
// 1,
// std::make_shared<ListNode>(
// 2,
// std::make_shared<ListNode>(
// 3,
// std::make_shared<ListNode>(
// 3,
// std::make_shared<ListNode>(
// 4,
// std::make_shared<ListNode>(
// 4,
// std::make_shared<ListNode>(
// 5
// ).get()
// ).get()
// ).get()
// ).get()
// ).get()
// ).get()
// );
printLinkedList(solutionObj.deleteDuplicates(head)); // [1,2,5]
head = new ListNode(1,new ListNode(1, new ListNode(1, new ListNode(2, new ListNode(3)))));
// head = std::make_shared<ListNode>(
// 1,
// std::make_shared<ListNode>(
// 1,
// std::make_shared<ListNode>(
// 1,
// std::make_shared<ListNode>(
// 2,
// std::make_shared<ListNode>(
// 3
// ).get()
// ).get()
// ).get()
// ).get()
// ).get();
printLinkedList(solutionObj.deleteDuplicates(head)); // [2,3]
return 0;
}
| |