কম্পিউটার টিউটোরিয়াল

C++-এ সোর্টেড লিস্ট থেকে ডুপ্লিকেট রিমুভ (Remove Duplicates from Sorted List)


একটি সোর্টেড লিংকড লিস্ট দেওয়া আছে। ডুপ্লিকেট নোডগুলো মুছে ফেলুন যাতে প্রতিটি উপাদান একবারই থাকে।

উদাহরণ: [1,1,2,3,3,3,4,5,5] -> [1,2,3,4,5]।

সমাধানের ধাপসমূহ

  • ডামি নোড (INT_MIN) তৈরি করুন, এর next = head।
  • curr = dummy।
  • যখন curr != null:
    • next = curr->next।
    • যখন next != null এবং next->val == curr->val: next = next->next।
    • curr->next = next; curr = next।
  • dummy->next রিটার্ন করুন।

C++ কোড উদাহরণ

#include <bits/stdc++.h>
using namespace std;

class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int data) { val = data; next = NULL; }
};

ListNode *make_list(vector<int> v) {
    ListNode *head = new ListNode(v[0]);
    for (int i = 1; i < v.size(); i++) {
        ListNode *ptr = head;
        while (ptr->next != NULL) ptr = ptr->next;
        ptr->next = new ListNode(v[i]);
    }
    return head;
}

void print_list(ListNode *head) {
    ListNode *ptr = head;
    cout << "[";
    while (ptr) { cout << ptr->val << ", "; ptr = ptr->next; }
    cout << "]" << endl;
}

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(INT_MIN);
        dummy->next = head;
        ListNode *curr = dummy;
        while (curr) {
            ListNode *next = curr->next;
            while (next && next->val == curr->val) next = next->next;
            curr->next = next;
            curr = next;
        }
        return dummy->next;
    }
};

int main() {
    Solution ob;
    vector<int> v = {1,1,2,3,3,3,4,5,5};
    ListNode *head = make_list(v);
    print_list(ob.deleteDuplicates(head));
    return 0;
}

ইনপুট

{1,1,2,3,3,3,4,5,5}

আউটপুট

[1, 2, 3, 4, 5, ]
  1. পাইথনে তালিকা থেকে ডুপ্লিকেট সরানোর পদ্ধতি

  2. জাভাস্ক্রিপ্টে লিংকড লিস্ট থেকে এলিমেন্ট রিমুভ করা

  3. জাভাস্ক্রিপ্টে সিঙ্গলি লিংকড লিস্ট থেকে এলিমেন্ট মুছে ফেলা

  4. Android-এ সর্টেড লিংকড লিস্ট থেকে ডুপ্লিকেট সরানোর পদ্ধতি