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

C প্রোগ্রামে এক্সট্রা স্পেস ছাড়া লিংকড লিস্ট উল্টে প্রিন্ট করা


ভূমিকা

একটি লিংকড লিস্ট দেওয়া থাকলে, এক্সট্রা স্পেস (রিকার্সন, স্ট্যাক, রিভার্স করা) ব্যবহার না করে O(1) স্পেসে উল্টে প্রিন্ট করতে হবে। পদ্ধতি: প্রথমে নোড কাউন্ট করুন, তারপর n থেকে 1 পর্যন্ত লুপ চালিয়ে i-তম নোড প্রিন্ট করুন।

উদাহরণ

ইনপুট: 10 → 21 → 33 → 42 → 89
আউটপুট: 89 42 33 21 10

এলগরিদম

int getCount(node* head) // নোড সংখ্যা বের করুন
int getNth(node* head, int n) // n-তম নোডের ডেটা রিটার্ন করুন
void reversePrint(node* head)
  n = getCount(head)
  i = n থেকে 1 পর্যন্ত: getNth(head, i) প্রিন্ট করুন

C প্রোগ্রাম উদাহরণ

#include 
#include 

struct node { int data; struct node* next; };

void push(struct node** head, int data) {
    struct node* newNode = malloc(sizeof(struct node));
    newNode->data = data;
    newNode->next = *head;
    *head = newNode;
}

int getCount(struct node* head) {
    int c = 0;
    while (head) { c++; head = head->next; }
    return c;
}

int getNth(struct node* head, int n) {
    for (int i = 0; i < n-1 && head; i++) head = head->next;
    return head->data;
}

void reversePrint(struct node* head) {
    int n = getCount(head);
    for (int i = n; i >= 1; i--)
        printf("%d ", getNth(head, i));
}

int main() {
    struct node* head = NULL;
    push(&head, 89); push(&head, 42); push(&head, 33);
    push(&head, 21); push(&head, 10);
    reversePrint(head);
    return 0;
}

আউটপুট

89 42 33 21 10
  1. সি প্রোগ্রামিং-এ O(1) এক্সট্রা স্পেসে n×n স্পাইরাল ম্যাট্রিক্স প্রিন্ট করা

  2. সি প্রোগ্রামিং-এ লিংকড লিস্টের বিকল্প নোড প্রিন্ট করা (ইটারেটিভ মেথড)

  3. সি প্রোগ্রামিং-এ লিংকড লিস্ট রিভার্স না করে রিভার্স অর্ডারে প্রিন্ট করা

  4. C প্রোগ্রামে অ্যারে লেফ্ট রোটেশন O(n) টাইম ও O(1) স্পেসে