Insert a node at the head of a linked list
The following is the solution to Hacker Rank problem Insert a node at the head of a linked list using Java. For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.
Score: 5/5
#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct Node
{
int data;
Node *next;
};/*
Insert Node at the begining
of a linked list
Initially head pointer
argument could be NULL for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
return back the pointer to the head of the linked list in the below
method.
*/
Node* Insert(Node *head,int data)
{
Node *newHead = new
Node();
// Complete this method
if(head!= NULL)
{
newHead->data =
data;
newHead->next =
head;
}
else
{
newHead->data =
data;
newHead->next =
NULL;
}
return newHead;
}void Print(Node *head)
{
Node *temp =
head;
while(temp!=
NULL){ cout<<temp->data<<"\n";temp = temp->next;}
}
int main()
{
int t;
cin>>t;
Node *head =
NULL;
while(t-- >0)
{
int
x; cin>>x;
head
= Insert(head,x);
}
Print(head);
}
|
No comments:
Post a Comment