Stack Mit verketteten Liste in C++

Ich versuche zu schaffen, einen stack mit verketteten Listen in c++. Aber das display-Funktion, die ich geschrieben habe gibt nur die Spitze des stack. Ich kann wirklich nicht verstehen, warum dies geschieht. Jede Hilfe oder Aufklärung sehr dankbar. Dank

#include<iostream.h>
#include<conio.h>

class Node
{
protected:

    Node* next;
    int data;

public:

    Node(int d){data=d;}
    friend class Stack;
};

class Stack
{
public:
    Stack(){top->next='\0';length=0;}

void push(int d)
{
    Node *n=new Node(top->data);
    n->next='\0';
    top->next=n;
    top->data=d;
    length++;
}

int pop()
{
    top=top->next;
    length--;
    return top->data;
}

void displaystack()
{
    while(top->next!='\0')
    {
        cout<<top->data<<endl;
    top=top->next;
    }
}

int getlength()
{
    return length;
}

private:
    Node *top;
    int length;

};

void main()
{
    clrscr();
    Stack s;
    s.push(9);
    s.push(8);
    s.push(7);
    s.push(6);
    s.push(5);
    s.push(3);
    s.displaystack();
    int len=s.getlength();
    cout<<"length of stack is "<<len<<endl;
    getch();
}

Er druckt nur die folgenden:
3
die Länge der Stapel 6

--------xxxxxxx-------xxxxxxxx--------xxxxxxx-----------xxxxxxxxxxxxx--------------

Nach der Bearbeitung der code sieht so aus:
und funktioniert auch! (Dank an @Kaathe) 😛

#include<iostream.h>
#include<conio.h>

class Node
{
protected:
Node* next;
int data;

public:

Node(int d){data=d;}
friend class Stack;
};

class Stack
{
public:
Stack(){top->next=NULL;length=0;}
~Stack()
{
     while(top!=NULL)
 {
   Node* toDelete=top;
   top=top->next;
   delete toDelete;
 }

}

void push(int d)
{
Node *n=new Node(d);
n->next=top;
top=n;
length++;
}

int pop()
{
 Node* oldtop=top;
 top=top->next;
 int oldtopdata=oldtop->data;
 delete(oldtop);
 --length;
 return oldtopdata;
}

void displaystack()
{
Node* current=top;
while(current->next!=NULL)
    {
    cout<<current->data<<endl;
    current=current->next;
    }
}

int getlength()
{
return length;
}

private:
Node *top;
int length;

};
  • Ich sehe nicht, wie Sie Sie initialisieren top of stack. "n->next='\0'; top->next=n;" sollte "n->next= top>next; top->next=n;"
  • Ich bin versucht zu kopieren der Daten von "oben" in n und machen Sie "top" auf "n" wie folgt : oben(Punkte, n)->n(Punkte auf null)
  • Danke!!! JackyZhu Hab!
Schreibe einen Kommentar