I don't know why my insert beginning node is not working. Help me!
#include <iostream>
using namespace std;
// declaring a Node
struct ListNode{
int data;
ListNode* next;
};
void firstNode (ListNode* head, int n)
{
head -> data = n;
head -> next = NULL;
}
// inserting a Node in singly linked list at the ending.
void addNode_ending (ListNode* head, int n)
{
ListNode* newNode = new ListNode;
newNode -> data = n;
newNode -> next = NULL;
ListNode* current = head;
while(current != NULL)
{
if(current -> next == NULL)
{
current -> next = newNode; // adding node at the ending.
return;
}
else if (current -> next != NULL)
{
current = current -> next;
}
}
}
// inserting a Node in single linked list at the begining.
void addNode_begining (ListNode* head, int n)
{
ListNode* newNode = new ListNode;
ListNode* current = head;
while(current != NULL)
{
newNode -> data = n;
newNode -> next = current;
current = newNode;
}
}
void print (ListNode* head)
{
ListNode* p = head;
while (p != NULL)
{
cout << p -> data << " ";
p = p -> next;
}
cout << endl;
}
int main()
{
ListNode* head = new ListNode;
Your function has more than one issue, but a fundamental one in it is the same as in the following sample:
1 2 3 4
int foo = 7;
int bar = foo;
bar = 42;
// why is the value of foo still 7?
The initial value of bar is a copy of the value of the foo at that time. The bar is an independent variable and therefore further changes to it do not affect the foo.
Similarly, the function argument head is a mere by value copy of the variable head of the main(), and the function variable current is a by value copy of the function argument head.