forked from fedeoliv/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert_node_specific.cpp
More file actions
64 lines (58 loc) · 1.07 KB
/
Copy pathinsert_node_specific.cpp
File metadata and controls
64 lines (58 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct Node
{
int data;
Node *next;
};/*
Insert Node at a given position in a linked list
The linked list will not be empty and position will always be valid
First element in the linked list is at position 0
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* InsertNth(Node *head, int data, int position)
{
Node *node = new Node();
node->data = data;
node->next = NULL;
Node *temp = head;
if(position == 0) {
node->next = head;
head = node;
} else {
for(int i = 1; i < position; i++)
temp = temp->next;
node->next = temp->next;
temp->next = node;
}
return head;
}void Print(Node* head)
{
while(head != NULL)
{
cout<<head->data;
head=head->next;
}
}
int main()
{
int t;
cin>>t;
Node *head = NULL;
head = new Node();
head->data = 2;
head->next = NULL;
while(t-- >0){
int x,n; cin>>x>>n;
head = InsertNth(head,x,n);
}
Print(head);
cout<<"\n";
}