Insert a node at the tail of a linked list
The following is the solution to Hacker Rank problem Insert a node at the tail 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 end of a
linked list
head pointer input could be
NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Insert(Node *head,int data)
{
// Complete this method
Node *headPtr = new Node();
headPtr = head;
if(head!=NULL)
{
while(head->next!=NULL)
{
head =
head->next;
}
Node *tail = new
Node();
tail->data = data;
tail->next = NULL;
head->next =
tail;
}
else
{
Node *tail = new
Node();
tail->data = data;
tail->next = NULL;
headPtr = tail;
}
return headPtr;
}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