-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFind_middle_and_nth_from_last_linked_list.cpp
104 lines (86 loc) · 1.94 KB
/
Find_middle_and_nth_from_last_linked_list.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct Node {
int data;
Node *next;
};
void forwardPrint(struct Node *head) {
if (head == NULL)
return;
cout << head->data << " ";
forwardPrint(head->next);
}
void insertEnd(Node **head, int data) {
Node *node = new Node();
Node *last = *head;
node->data = data; // Insert data in new node
node->next = NULL; // link new node to NULL as it is last node
if (*head == NULL) { // if list is empty add in beginning.
*head = node;
return;
}
while (last->next != NULL) // Find the last node
last = last->next;
last->next = node; // Add the node after the last node of list
return;
}
/* struct Node
{
int data;
Node* next;
};
Above structure is used to define the linked list, You have to complete the below functions only */
int findMiddle(Node *head) {
// Write your code here
int len = 0;
if(head == NULL)
return -1;
if(head->next == NULL)
return 1;
Node *temp = head;
while(temp) {
len++;
temp = temp->next;
}
temp = head;
for (int i = 0; i < len/2; i++) {
temp = temp->next;
}
return temp->data;
}
int findNLast(Node *head, int n) {
// Write your code here
if(head == nullptr || n <= 0)
return -1;
Node *p = head, *q = head;
for (int i = 0; i < n; i++){
if(p->next == NULL)
return p->data;
p = p->next;
}
while(p) {
q = q->next;
p = p->next;
}
return q->data;
}
int main() {
int t, n, m;
cin >> t;
while (t--) {
Node *head = NULL;
Node *t1, *t2;
int k, ans;
cin >> n;
while (n--) {
cin >> m;
insertEnd(&head, m);
}
cin >> k;
cout << findMiddle(head) << endl;
cout << findNLast(head, k) << endl;
}
return 0;
}