Learning to implement a Linked List Stack class in C++ -


i want implement linked list using stack. here class:

class linkedliststack { public:     linkedliststack();     void push(int x);     void pop();     int peek();  private:     struct node     {         int data;         node *next;     };     node *head;     node *tail; }; 

my implementation far:

linkedliststack::linkedliststack() {     m_headptr = 0;     m_tailptr = 0; }  void linkedliststack::push(int x) {     struct node* newnode = (struct node*) malloc(sizeof(struct node));     newnode->data = x;     newnode->next = head;     head = newnode; }  void linkedliststack::pop() {     struct node* newnode = (struct node*) malloc(sizeof(struct node));     newnode->data = null;     newnode->next = head;     head = newnode;     delete newnode; }  int linkedliststack::peek() {     return head->data; } 

as of now, push , peek seem working, pop not work. please help. want keep implementation/style same, want fix error make work.

i think wrote pop method wrong. you're inserting new item. hope works.

void linkedliststack::pop() {     if (head != 0)     {         struct node* newhead = head->next;         delete head;         head = newhead;     } } 

Popular posts from this blog