-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find the sum of last n nodes of the linked list
78 lines (61 loc) · 1.69 KB
/
Find the sum of last n nodes of the linked list
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
//Find the sum of last n nodes of the linked list
import java.io.*;
import java.util.*;
class Node {
int data;
Node next;
Node(int a) {
data = a;
next = null;
}
}
class Node {
int data;
Node next;
public Node (int data){
this.data = data;
this.next = null;
}
}
class Solution {
public int sumOfLastN_Nodes(Node head, int n) {
Node cur = head;
int size = 0;
while(cur != null) {
size++;
cur = cur.next;
}
int sum = 0;
for(int i = 0; i < size - n; i++) {
head = head.next;
}
while(head != null) {
sum += head.data;
head = head.next;
}
return sum;
}
}
class LinkedList {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
ArrayList<Integer> arr = new ArrayList<>();
String input = br.readLine();
StringTokenizer st = new StringTokenizer(input);
while(st.hasMoreTokens()) {
arr.add(Integer.parseInt(st.nextToken()));
}
int n = Integer.parseInt(br.readLine());
Node head = new Node(arr.get(0));
Node tail = head;
for(int i = 1; i < arr.size(); ++i) {
tail.next = new Node(arr.get(i));
tail = tail.next;
}
Solution ob = new Solution();
System.out.println(ob.sumOfLastN_Nodes(head, n));
}
}
}