473,769 Members | 2,140 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

implementing stack

Ben
Hi all,

I implemented a stack in C++ in 2 different ways and I'd like to know
which approach is better than the other.. and if there is any
difference between the two? I'd also like to know if the destructor
i'm using is correct.. I got segmentation fault in my second approach
while I quit the program. I appreciate any help....

My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;

/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
}
void push(int);
void pop();
void print();
};

My second approach is without the struct:

/* Stack class */
class dynamic_stack {
dynamic_stack *head;
dynamic_stack *tail;
dynamic_stack *cur;
int NumNodes;
int data;
dynamic_stack *next;
dynamic_stack *prev;

public:
dynamic_stack() ;
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes=data=0 ;
delete next; delete prev;
}
void push(int);
void pop();
void print();
};

Thanks a lot!
Ben
Jul 22 '05 #1
8 2740
Ben wrote:
Hi all,

I implemented a stack in C++ in 2 different ways and I'd like to know
which approach is better than the other.. and if there is any
difference between the two? I'd also like to know if the destructor
i'm using is correct.. I got segmentation fault in my second approach
while I quit the program. I appreciate any help....

My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;
Leave out the typedef. It's not needed. I'd also rather name it "node"
or something instead of list, because it isn't a list, but rather only
one node of it.

struct node {
int data;
node* next;
node* prev;
};
/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
It's good habit to prefer initialization over assignment. So this should
look like:

dynamic_stack()
: head(0),
tail(0),
cur(0),
NumNodes(0)
{}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
Setting NumNodes to 0 is not really needed here, because the object
won't exist anymore after the destructor finished.
}
void push(int);
void pop();
void print();
};

My second approach is without the struct:

/* Stack class */
class dynamic_stack {
dynamic_stack *head;
dynamic_stack *tail;
dynamic_stack *cur;
int NumNodes;
int data;
dynamic_stack *next;
dynamic_stack *prev;

public:
dynamic_stack() ;
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes=data=0 ;
delete next; delete prev;
}
void push(int);
void pop();
void print();
};

Thanks a lot!


I'd prefer the one with the struct. You could put that struct into the
private section of class dynamic_stack.

Jul 22 '05 #2
"Ben" <cr*********@ya hoo.com> wrote in message
My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;

/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
}
Why are there 3 nodes (head, tail, cur)? In the destructor, you delete only
3 nodes, so is there a memory leak? Plus, what happens for a stack of 1
element; do you delete the same node twice?

My second approach is without the struct:

/* Stack class */
class dynamic_stack {
dynamic_stack *head;
dynamic_stack *tail;
dynamic_stack *cur;
int NumNodes;
int data;
dynamic_stack *next;
dynamic_stack *prev;

public:
dynamic_stack() ;
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes=data=0 ;
delete next; delete prev;
}
void push(int);
void pop();
void print();
};


The reason for the crash is probably because the destructor deletes the same
node twice. But again you seem to have a memory leak as you delete at most
5 nodes.

The first way seems better to me as you can implement a generic double
linked list, and then adapt this to the interface of a stack. So it's two
for the price of one :).
Note in the standard you can use

std::stack<int> stack1;
std::stack<int, std::deque<int> > stack2;
stack1 = stack2; // OK, same type
std::stack<int, std::list<int> > stack3;
Jul 22 '05 #3

Ben, the destructors in both don't seem to be right, I would expect
to see a loop to visit all the list-nodes and delete each of them.
I'm also a bit suspicious of what happens when you have 1 or 2
items in the list, it looks to me that head and tail might be deleted
twice, what about cur too?

You have a pop() operation, but there's no way to get the value of
the top of the stack, such as int top().
"Ben" <cr*********@ya hoo.com> wrote in message
news:d9******** *************** ***@posting.goo gle.com...
Hi all,

I implemented a stack in C++ in 2 different ways and I'd like to know
which approach is better than the other.. and if there is any
difference between the two? I'd also like to know if the destructor
i'm using is correct.. I got segmentation fault in my second approach
while I quit the program. I appreciate any help....

My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;

/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
}
void push(int);
void pop();
void print();
};

My second approach is without the struct:

/* Stack class */
class dynamic_stack {
dynamic_stack *head;
dynamic_stack *tail;
dynamic_stack *cur;
int NumNodes;
int data;
dynamic_stack *next;
dynamic_stack *prev;

public:
dynamic_stack() ;
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes=data=0 ;
delete next; delete prev;
}
void push(int);
void pop();
void print();
};

Thanks a lot!
Ben

Jul 22 '05 #4
Ben
Rolf Magnus <ra******@t-online.de> wrote in message news:<c9******* ******@news.t-online.com>...

I'd prefer the one with the struct. You could put that struct into the
private section of class dynamic_stack.


why is the first approach (with struct) better than the second one?
are there any performance issues or other overhead involved in the
second approach?
Thanx
Ben
Jul 22 '05 #5
Ben
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message news:<HF******* **************@ bgtnsc05-news.ops.worldn et.att.net>...
"Ben" <cr*********@ya hoo.com> wrote in message
My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;

/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
}


Why are there 3 nodes (head, tail, cur)? In the destructor, you delete only
3 nodes, so is there a memory leak? Plus, what happens for a stack of 1
element; do you delete the same node twice?


head, tail and cur are used in pop() and print() functions... perhaps
they are redundant- i haven't carefully looked at them.. i'm just
trying to do it my own way to make it work... my code works fine.. all
i'm concerned about now is the destructor. I'm not quite sure if I
have to delete *next and *prev pointers as well... I'm worried if I've
designed it the right way... Dave suggested that i have to use a loop
to delete each node..
Jul 22 '05 #6
"Ben" <cr*********@ya hoo.com> wrote in message
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message

news:<HFHwc.408 94

Why are there 3 nodes (head, tail, cur)? In the destructor, you delete only 3 nodes, so is there a memory leak? Plus, what happens for a stack of 1
element; do you delete the same node twice?


head, tail and cur are used in pop() and print() functions... perhaps
they are redundant- i haven't carefully looked at them.. i'm just
trying to do it my own way to make it work... my code works fine.. all
i'm concerned about now is the destructor. I'm not quite sure if I
have to delete *next and *prev pointers as well... I'm worried if I've
designed it the right way... Dave suggested that i have to use a loop
to delete each node..


Seems you need only one node (for the top). You could also have 2 nodes
(for the top and bottom). Anyway, if the top node is NULL then it means you
have no elements. If you have one element the top node points to a node,
but this node's next pointer is NULL.

As for print, etc, you can create a local variable node * cur = member_top.

And yes, Dave's suggestion is correct.
Jul 22 '05 #7
AHHHGG!
Ben, This is horrible! I think you've not factored the functionality
properly
between the Stack and the "storage" or list class:-

A stack can be implemented by using a list or an array, the essence of the
stack is you only care about the head or the "top", so there's a lot of
unnecessary
cruft in your list struct ( or more accurately a "node" class) dealing with
tails & curs.

Secondly, I'd want the list to be a bit smarter than the class you've
provided, I'd want to
do useful, powerful things like insert a node, get a node remove a node,
tell me if the list is empty.

Thirdly, a stack is a more "specialize d" data structure than the list in
that operations are
solely performed at the head, it would seem that I could easily adapt a list
to perform operations
at the head of the list and I'd get my stack class. Typically, this
specialization is performed by "wrapping" a list class member inside the
stack class and implementing the stack operations by "forwarding " to
particular member list operations:

class Stack
{
public:
// constructor/destructor stuff not show.
public:
// error checking for empty stack omitted for illustration
void push( int e){ _list.insert_at _head(e); } // forwarding operation.
int pop( ) { return _list.remove_at _head( );}
int top( ) { return _list.element_a t_head();
bool isempty(){ return _list.isempty() ;}
private:
list _list;
};

So, the Stack is a simple shell or wrapper over the list class which has all
the brains.
In this model, the destruction of the Stack is trivial, the _list member is
automatically
destroyed, the list class should provide the destruction behavior to loop
over the remaining
nodes left in the list and destroy them.

hope that helps!
dave

"Dave Townsend" <da********@com cast.net> wrote in message
news:7u******** ************@co mcast.com...

Ben, the destructors in both don't seem to be right, I would expect
to see a loop to visit all the list-nodes and delete each of them.
I'm also a bit suspicious of what happens when you have 1 or 2
items in the list, it looks to me that head and tail might be deleted
twice, what about cur too?

You have a pop() operation, but there's no way to get the value of
the top of the stack, such as int top().
"Ben" <cr*********@ya hoo.com> wrote in message
news:d9******** *************** ***@posting.goo gle.com...
Hi all,

I implemented a stack in C++ in 2 different ways and I'd like to know
which approach is better than the other.. and if there is any
difference between the two? I'd also like to know if the destructor
i'm using is correct.. I got segmentation fault in my second approach
while I quit the program. I appreciate any help....

My first appoach goes like this:

/* List struct */
typedef struct list {
int data;
list *next;
list *prev;
} list;

/* Stack class */
class dynamic_stack {
list *head;
list *tail;
list *cur;
int NumNodes;

public:
dynamic_stack() {
head = tail = cur = NULL;
NumNodes = 0;
}
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes = 0;
}
void push(int);
void pop();
void print();
};

My second approach is without the struct:

/* Stack class */
class dynamic_stack {
dynamic_stack *head;
dynamic_stack *tail;
dynamic_stack *cur;
int NumNodes;
int data;
dynamic_stack *next;
dynamic_stack *prev;

public:
dynamic_stack() ;
~dynamic_stack( ) {
delete head; delete tail; delete cur;
NumNodes=data=0 ;
delete next; delete prev;
}
void push(int);
void pop();
void print();
};

Thanks a lot!
Ben


Jul 22 '05 #8
An approach better than both these is to use the std::stack class template.

!!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!
To iterate is human, to recurse divine.
-L. Peter Deutsch
!!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
426
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions have been asked on clc before so it is probably OK. I am a newbie to C++. BS 3rd edition states: % The throw transfers control to a handler for exceptions .... %
2
3398
by: Ole Nielsby | last post by:
First, bear with my xpost. This goes to comp.lang.c++ comp.lang.functional with follow-up to comp.lang.c++ - I want to discuss an aspect of using C++ to implement a functional language, and I'd like the attention of fp as well as C++ gurus if available. The language I'm implementing - PILS - is dynamically
0
2336
by: raghuveer | last post by:
i want to implement multiple stacks using arrays..I am able to create ,insert and print them but not poping an element form any of the stack..This is what i have #include<stdio.h> #include<conio.h> int top; int bot; void main() {
9
7829
by: raylopez99 | last post by:
What's the best way of implementing a multi-node tree in C++? What I'm trying to do is traverse a tree of possible chess moves given an intial position (at the root of the tree). Since every chess position has around 30 moves, it would mean every node of the tree would have 30 branches (on average), which in turn themselves would average about 30 branches each. I can think of a variety of ways of implementing this, including a series...
3
2005
by: rami.mawas | last post by:
I have implemented an RPN calculator in python but now I would like to make the stack size fixed. how can I transform the user's RPN expression from a stack overflow to a computable expression. For instance, if my stack size is 2 then the some expression can't be computed but could be transformed as following: Non computable expression: 1 2 3 + + --stack size of 3 is needed Computable expression: 1 2 + 3 + --stack size of 2...
13
5042
by: Tristan Wibberley | last post by:
Hi I've got implementing overloaded operator new and delete pretty much down. Just got to meet the alignment requirements of the class on which the operator is overloaded. But how does one implement operator new/delete I can't see a way to indicate, on delete, how many objects must be destroyed (or how big the space is) - alternatively I can't figure out what are the alignment requirements so that the implementation, after calling my...
3
1780
by: xr0krx | last post by:
Hi, Im having some problems with my program. I'm kinda new to this stuff; only been doing this for about a month. What it's suppose to do is ask the user to input a word, and then print out the word in reverse order. It's basically using the pop/push idea...sorta. I've tried a variety of ways to convert the string to char to get it to print, but all of them havent worked. Any ideas? Here's where I ended up... #include <iostream.h>...
3
1965
by: Saman.Jahanpour | last post by:
Hi my friends, I want to implement a CHAT section on my website and I do not know anything about it. I want help from someone or some people here to tell me what I need to know and what I need to learn. I heard that I need to know Threading and Socket Programming, is that true? Tell me please. I haven't found any specific article about threading in PHP.
14
3196
by: Ellipsis | last post by:
Ok so I am converting to hexadecimal from decimal and I can only cout the reverse order of the hexadecimal?! How could I reverse this so its the right order? Heres my code: #include <iostream> using namespace std; void binary(int number) { int remainder; if(number <= 1)
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9422
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10208
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10038
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.