Can anyone help me with a singly linked list? I know how to do it with struct, but now i wanna know how to do it with only arrays and pointers without struct or nodes.Algorithms please thank you.
#include <iostream>
using namespace std;
const int size=5;
int data[size];
int *mem;
int add[size];
int top = -1;
void AddLast(int value)
{
if(top==-1)
{
top=data[value];
}
else
{
top++;
top=data[value];
}
}
void print()
{ cout << "Queue: ";
for(int i = 0; i != top; i = (i + 1) % size)
{
cout << data[i] << "->";
}
cout << endl;
}
int main()
{
AddLast(2);
print();
AddLast(3);
print();
AddLast(4);
print();
cin.get();
return 0;
}
I want to addlast, addfirst, and add sorted... is this the way?
You can't do it with only one array, you need at least two: One for the data and one for the links. If you don't want to use structures at all (though I don't really see the reason for it) you could have multiple data arrays.
The data array contains the actual data, it's nothing special with it. The link array contains indexes to the data array, where each index is a "next" pointer.
For example, lets say you want to have a linked list of integers, and you have three integers in the list (their values are irrelevant), lets call that data array
d
, then you haved[0]
,d[1]
andd[2]
. The first node in the list isd[1]
, followed byd[0]
and lastd[2]
. Then you need a head variable, which tells which index is the head of the list, this head variable is initialized to1
(and "points" tod[1]
). Then we have the link array, lets call itl
, since the head is "pointing" to1
we fetchl[1]
to get the next node, the contents ofl[1]
is0
which tells us the next node isd[0]
. To get the next node we checkl[0]
which gives us2
ford[2]
. The next link,l[2]
could be-1
to mark the end of the list.Of course, the data array(s) and the link array needs to be of the same size.