-
Notifications
You must be signed in to change notification settings - Fork 54
/
appending in LinkedList.cpp
70 lines (65 loc) · 1.03 KB
/
appending in LinkedList.cpp
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
65
66
67
68
69
70
#include<iostream>
using namespace std;
#include "node.cpp"
node* takeInput(){
node* head = NULL;
node* tail = NULL;
int data;
cin >> data;
while(data != -1){
node* newNode = new node(data);
if(head == NULL){
head = newNode;
tail = newNode;
}
else{
tail -> nxt = newNode;
tail = tail -> nxt;
}
cin >> data;
}
return head;
}
void print(node* head){
node* temp = head;
while(temp != NULL){
cout << temp -> data << " ";
temp = temp -> nxt;
}
cout << endl;
}
int length(node* head){
if(head == NULL){
return 0;
}
return 1 + length(head -> nxt);
}
node* append(node* head, int m){
int l = length(head);
node* temp = head;
while(temp -> nxt != NULL){
temp = temp -> nxt;
}
temp -> nxt = head;
node* t = head;
for(int i = 1; i < (l - m); i++){
t = t -> nxt;
}
head = t -> nxt;
t -> nxt = NULL;
return head;
}
int main(){
int n;
cin >> n;
int i = 0;
while(i < n){
int m;
node* head = takeInput();
cin >> m;
head = append(head,m);
print(head);
i++;
}
return 0;
}