class
Node {
int
data;
Node next;
public
Node(
int
data) {
this
.data = data;
this
.next =
null
;
}
}
public
class
SublistSumJava {
static
boolean
hasSublistWithSumK(Node head,
int
K) {
if
(head ==
null
) {
return
false
;
}
Node start = head;
Node end = head;
int
sum =
0
;
while
(end !=
null
) {
sum += end.data;
while
(sum > K) {
sum -= start.data;
start = start.next;
}
if
(sum == K) {
return
true
;
}
end = end.next;
}
return
false
;
}
static
Node createNode(
int
data) {
Node newNode =
new
Node(data);
return
newNode;
}
public
static
void
main(String[] args) {
Node head1 = createNode(
2
);
head1.next = createNode(
4
);
head1.next.next = createNode(
1
);
head1.next.next.next = createNode(
6
);
head1.next.next.next.next = createNode(
7
);
head1.next.next.next.next.next = createNode(
2
);
head1.next.next.next.next.next.next = createNode(
9
);
int
K1 =
15
;
if
(hasSublistWithSumK(head1, K1)) {
System.out.println(
"Yes"
);
}
else
{
System.out.println(
"No"
);
}
Node head2 = createNode(
3
);
head2.next = createNode(
2
);
head2.next.next = createNode(
1
);
head2.next.next.next = createNode(
7
);
head2.next.next.next.next = createNode(
8
);
head2.next.next.next.next.next = createNode(
5
);
int
K2 =
9
;
if
(hasSublistWithSumK(head2, K2)) {
System.out.println(
"Yes"
);
}
else
{
System.out.println(
"No"
);
}
}
}