SORU
26 Kasım 2009, PERŞEMBE


Nasıl tek bağlı bir liste sadece iki işaretçileri kullanarak tersine çevirmek için?

Eğer biraz mantık bağlantılı liste sadece iki işaretçileri kullanarak ters varsa orada merak olurdum.

Aşağıdaki tek bağlantılı liste üç işaretçiler yani p, r, s: kullanarak tersine çevirmek için kullanılır

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

void reverse()
{
    struct node *p = first,
                *q = NULL,
                *r;
    while (p != NULL)
    {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }
    q = first;
}

Başka bir alternatif bağlı listeyi tersine çevirmek için var mı? en iyi mantık tek bağlı listeyi ters çevirmek için, zaman karmaşıklığı açısından ne olurdu?

CEVAP
26 Kasım 2009, PERŞEMBE


Herhangi bir alternatif? Hayır, bu kadar basit, ve bunu yaparken temelde farklı yolu var. Bu algoritma zaten O(n) zaman alır, ve her düğüm değiştirmeniz gerekir gibi herhangi bir daha hızlı alabilirsiniz.

Kodunuzu doğru yolda gibi görünüyor, ama oldukça formda yukarıda çalışmıyor. Burada çalışan bir versiyonu:

#include <stdio.h>

typedef struct Node {
  char data;
  struct Node* next;
} Node;

void print_list(Node* root) {
  while (root) {
    printf("%c ", root->data);
    root = root->next;
  }
  printf("\n");
}

Node* reverse(Node* root) {
  Node* new_root = 0;
  while (root) {
    Node* next = root->next;
    root->next = new_root;
    new_root = root;
    root = next;
  }
  return new_root;
}

int main() {
  Node d = { 'd', 0 };
  Node c = { 'c', &d };
  Node b = { 'b', &c };
  Node a = { 'a', &b };

  Node* root = &a;
  print_list(root);
  root = reverse(root);
  print_list(root);

  return 0;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Amazon Web Services

    Amazon Web S

    8 NİSAN 2009
  • Bigapplemagic

    Bigapplemagi

    22 EYLÜL 2011
  • pjtoohot

    pjtoohot

    15 NİSAN 2008