Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a linked list on the stack in C++?

I just started learning C++ couple of weeks ago. So now I have this school assignment problem that asks me to implement a linked-list without using "new" or anything to do with dynamically allocating memory (and cannot use any ADT from STL). The prof says that everything can be done on the stack, but how? I have been working on this since Friday and still stuck on this with absolutely no luck.

It says: Keep a stack of the file names being read. Use the following data structure for the stack:

struct Node { 
string fileName; 
Node *link; 
}; 

I tried to avoid using new but it always give me "segmentation fault" or "BUS error" when I pass the head of the list into a recursive method call. Any ideas about how I can work around this??

like image 320
cplusplusNewbie Avatar asked Oct 12 '09 20:10

cplusplusNewbie


People also ask

Can linked lists be created on the stack?

The linked list can be implemented on the stack memory as well. Below is the C++ implementation of creating a linked list in stack memory: C++

Does stack require linked list?

A. Queues require linked lists, but stacks do not.

Can LinkedList be used as stack queue list?

In general, Stacks and Queues can be implemented using Arrays and Linked Lists . The reason you would use Linked List for implementing Stack is when you need a functionality involving LAST IN FIRST OUT form and you are not sure how many elements that functionality requires.

Can we implement stack using array and linked list?

We can implement stack using both array and linked list however it's better to use a liked list as it's a good practice to use memory efficiently and dynamically however for beginners and while learning or understanding how a Stack works to simplfy things we can use array implementation of a Stack.


1 Answers

The difference between heap and stack are mainly (not only, but for the sake of this question mainly) where the memory is allocated and how it is freed. When you want to allocate a node on the heap, you say new Node and the system will provide you with the memory, keeps track of which chunks are used and which ones are free, and provides you with the means to free a chunk once you don't need it any longer.

But you can just as well have a pool of nodes in an array on the stack. (Automatic variables are stack variables.) You can "allocate" from that pool, keep track of which nodes in the array are used and which are free, and mark unused ones as free ones you don't need them any longer. However, since the array's size is fixed at compile-time, this means that you have a maximum length for your list.

like image 127
sbi Avatar answered Sep 17 '22 13:09

sbi