2D array to simulate linked list
Feb 14, 2013 at 2:26am UTC
I'm trying to implement 2d array to simulate linked list for stack and I faced several difficulties doing so.
How do I implement from Top to Bottom ordering?
How do I check random index value for validity (I need to add a value at the top of the stack in a valid random space of the 2d array)
Source-code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#include <iostream>
using namespace std;
int myTop, index, nex = -1;
int twoDimentionalArray[25][3], L[25];
void construction(int twodimention[25][3], int list[25])
{
myTop = -1;
for (int p=0; p<25;p++)
twoDimentionalArray[p][2] = -1;
}
void empty()
{
if (myTop == -1)
cout << "The stack is empty." ;
else
cout << "The stack is not empty." ;
}
void push(int value)
{
if (myTop < 24)
{
myTop++;
L[myTop] = value;
index = rand()%25;
twoDimentionalArray[index][0] = index;
twoDimentionalArray[index][1] = value;
twoDimentionalArray[index][2] = nex;
nex = index;
}
else
cout << "The stack is full." ;
}
void top()
{
if (myTop != -1)
cout << "The top of stack value is: " << L[myTop];
else
cout << "The stack is empty." ;
cout << endl;
}
void pop()
{
if (myTop != -1)
{
myTop --;
twoDimentionalArray[index][2] = -1;
}
}
void display()
{
for (int row=0; row<25; row++)
{
for (int column=0; column<3; column++)
{
cout << twoDimentionalArray[row][column] << "\t" ;
if (column == 2)
cout << endl;
}
}
cout << endl;
}
int main()
{
construction(twoDimentionalArray, L);
for (int i=0; i < 11; i++)
push(i);
display();
system ("pause" );
}
Here's what I got from pushing 10 elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
0 3 9
0 0 -1
0 0 -1
3 6 24
0 0 -1
5 10 14
0 0 -1
0 0 -1
8 7 3
9 2 17
0 0 -1
0 0 -1
12 8 8
0 0 -1
14 9 12
0 0 -1
16 0 -1
17 1 16
0 0 -1
19 4 0
0 0 -1
0 0 -1
0 0 -1
0 0 -1
And one more thing: how do I get straight 0 from 25 index in the first coulumn? Thanks!
Last edited on Feb 14, 2013 at 2:28am UTC
Topic archived. No new replies allowed.