-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add K Nodes.java
54 lines (46 loc) · 1.24 KB
/
Add K Nodes.java
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
import java.util.* ;
import java.io.*;
/**********************************************************
Following is the class structure of the Node class:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
***************************************************************/
public class Solution {
public static Node getListAfterAddingNodes(Node head, int k) {
if (head==null){
return null;
}
int sum=0;
int count=0;
Node current=head;
Node prev=null;
while(current!=null){
count++;
sum+=current.data;
if(count==k){
Node temp=new Node(sum);
temp.next=current.next;
current.next=temp;
current=current.next;
count=0;
sum=0;
}
prev=current;
current=current.next;
}
if (count<k && count>0 ){
Node temp=new Node(sum);
prev.next=temp;
temp.next=null;
}
// for(int i=0)
return head;
// Write your code here.
}
}