There are three problems in the code of your push function:
void push(node* x, int y){
node *temp = new node();
if (x == NULL) {
temp->next = x;
temp->data = y;
x = temp;
}
else {
node *temp1 = new node(); temp1 = x; while (temp1->next != NULL) {
temp1 = temp1->next;
}
temp1->next = temp;
temp->data = y;
temp->next = NULL;
delete temp1;
}
}
To solve the first problem you need to pass a pointer to a pointer (as long as you are working in C; in C++ you could use a reference parameter). This will look like this:
void push (node** ppAnchor, int value)
{
...
To eliminate the second and third problem I would suggest that you run with a pointer over your existing list and make that pointer always point to the place where a new node can be attached; like this:
void push (node** ppAnchor, int value)
{
node** pLink = ppAnchor;
while (*pLink != NULL)
pLink = &(*pLink)->next;
Now pLink is pointing the
next
member of the last node in the list or to the anchor of the list if it is empty. So it points exactly to the location where you want to attach your new node. The rest is simple:
node* pNode = new node;
pNode->data = data;
pNode->next = NULL;
*pLink = pNode;
}
In your main you call the function like this:
int main()
{
node* head = NULL;
push (&head, 2);
A last remark: I would call that function
append
instead of
push
, as it attaches the new element to the end of the list.
Attaching the new element at the begin of the list is even easier than that and doesn't need the while-loop. I leave that as an exercise to you.
Now, that while-loop may get a performance problem if your lists grow to a large size. Therefore, it would be clever to also store a pointer to the last element of the list. To do that, I would define a new structure called
List
that contains both pointers. Try that also as an exercise.