83. remove duplicates from sorted list solution in c++
Here is a solution in C++ to remove duplicates from a sorted list, along with explanations for each step:
#include <iostream>
#include <vector>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode deleteDuplicates(ListNode head) {
// Check if the list is empty or contains only one node
if (head == NULL || head->next == NULL) {
return head;
}
// Create a pointer to keep track of the current node
ListNode* current = head;
// Traverse the list
while (current->next != NULL) {
// Check if the current node's value is equal to the next node's value
if (current->val == current->next->val) {
// If so, skip the next node by updating the current node's next pointer
current->next = current->next->next;
} else {
// If not, move to the next node
current = current->next;
}
}
return head;
}
int main() {
// Create a sorted list with duplicates
ListNode* head = new ListNode(1);
head->next = new ListNode(1);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(3);
head->next->next->next->next = new ListNode(3);
// Print the original list
ListNode* current = head;
while (current != NULL) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
// Remove duplicates from the list
ListNode* newHead = deleteDuplicates(head);
// Print the updated list
current = newHead;
while (current != NULL) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
return 0;
}
Explanation of the solution:
The
deleteDuplicates
function takes a pointer to the head of a linked list and returns a pointer to the head of the list after removing duplicates.We first check if the list is empty or contains only one node. If so, we return the head as it is, since there are no duplicates to remove.
We create a pointer
current
to keep track of the current node while traversing the list.We then traverse the list using a while loop until the current node's next pointer is NULL.
Inside the loop, we check if the current node's value is equal to the next node's value. If they are equal, it means we have a duplicate.
In this case, we skip the next node by updating the current node's next pointer to point to the node after the next node, effectively removing the duplicate node from the list.
If the values are not equal, we move to the next node by updating the current pointer.
After the loop ends, we return the head of the list.
In the
main
function, we create a sorted list with duplicates for testing purposes.We then print the original list to verify its contents.
We call the
deleteDuplicates
function to remove duplicates from the list, and store the new head in thenewHead
pointer.Finally, we print the updated list to verify that the duplicates have been removed.
This solution has a time complexity of O(n), where n is the number of nodes in the linked list, as we traverse the list only once.