-
Singly-linked list
I want to add an element to the list before the selected one. could anyone fix my code? Because it doesn't work for me.
Code:
List *get(int n)
{
List *pcurr = h;
for (int i = 0; i < n; i++) pcurr = pcurr->n;
return pcurr;
}
void add(int n, int x)
{
List *pnew = new List;
List *pcurr = get(n);
pnew->x = x;
if (h == NULL)
{
h = pnew;
pnew->n = pnew;
}
else
{
pnew->n = pcurr;
pcurr->n->n = pnew;
if (n == 0) h = pnew;
}
}
-
Can you explain me what your code do?
I fear that you just copy the code from somewhere else, which is ok if you say so :)
//also it seems that h is a global variable
-
Well, I just pasted a part of my function. Here's the rest:
Code:
struct List
{
int x;
List *n;
List *p;
};
List *h;
void init()
{
h = NULL;
}
Function 'get' gets an index of the particular element. Now I want to create a function that would add an element before the one returned from get, however it's quite problematic for me. (it doesn't work properly)
-
Perform the whole operation in a piece of paper. Then think of the steps you followed in the paper and transform them to an algorithm. Be aware of not losing your pointers!!
Moreover, you see here the code I use for a simple linked list. It has comments for every line!
//it's in c, but you will get the idea with the pointers.
Also mind that in C++ we use classes instead of structs.
-
Code:
if (h == NULL)
{
h = pnew;
pnew->n = pnew;
}
That code looks a bit odd. Although it could be your intention, this creates a circular linked-list which does not seem to be what you truly want. Do you mean to set the next/previous pointers to NULL here? I'm guessing that the n/p pointers mean next/previous. The rest of your code does not appear to deal with the p/previous pointer as it should and this would make the given code sample a doubly linked list and not a singly linked list.
-
You simply cannot do it the way you are trying to do it.
To insert before an item you need a pointer to the item before that, which your 'get' function will not give you. Find another way.