Eliminate duplicates from LL
Eliminate duplicates from LL
Send Feedback
Eliminate duplicates from LL
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first and the only line of each test case or query contains the elements(in ascending order) of the singly linked list separated by a single space.
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element.
For each test case/query, print the resulting singly linked list of integers in a row, separated by a single space.
Output for every test case will be printed in a seperate line.
1 <= t <= 10^2
0 <= M <= 10^5
Time Limit: 1sec
Where 'M' is the size of the singly linked list.
1
1 2 3 3 3 3 4 4 4 5 5 7 -1
1 2 3 4 5 7
2
10 20 30 40 50 -1
10 10 10 10 -1
10 20 30 40 50
10
/**************************************************************** Following is the class structure of the Node class:
class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } };
*****************************************************************/
Node *removeDuplicates(Node *head){ //Write your code here if(head == NULL||head->next == NULL){ return head; } Node* temp = head; while(temp->next != NULL){ if(temp->data == temp->next->data){ temp->next = temp->next->next; }else{ temp = temp->next; } } return head;}
#include <iostream>
class Node{public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; }};
using namespace std;#include "solution.h"
Node *takeinput(){ int data; cin >> data; Node *head = NULL, *tail = NULL; while (data != -1) { Node *newnode = new Node(data); if (head == NULL) { head = newnode; tail = newnode; } else { tail->next = newnode; tail = newnode; } cin >> data; } return head;}
void print(Node *head){ Node *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl;}
int main(){ int t; cin >> t; while (t--) { Node *head = takeinput(); head = removeDuplicates(head); print(head); } return 0;}
Comments
Post a Comment