class
ListNode {
int
val;
ListNode next;
public
ListNode(
int
x) {
val = x;
next =
null
;
}
}
public
class
MinimumSublistSum {
public
static
ListNode findMinimumSublist(ListNode head,
int
k) {
ListNode current = head;
ListNode minStart =
null
;
int
minLen = Integer.MAX_VALUE;
while
(current !=
null
) {
int
sum_val =
0
;
int
len =
0
;
ListNode temp = current;
while
(temp !=
null
) {
sum_val += temp.val;
len++;
if
(sum_val == k) {
if
(len < minLen) {
minLen = len;
minStart = current;
}
}
temp = temp.next;
}
current = current.next;
}
return
minStart;
}
public
static
void
printList(ListNode head) {
while
(head !=
null
) {
System.out.print(head.val +
" -> "
);
head = head.next;
}
System.out.println(
"NULL"
);
}
public
static
void
main(String[] args) {
ListNode head1 =
new
ListNode(
4
);
head1.next =
new
ListNode(
6
);
head1.next.next =
new
ListNode(
1
);
head1.next.next.next =
new
ListNode(
2
);
head1.next.next.next.next =
new
ListNode(
5
);
head1.next.next.next.next.next =
new
ListNode(
3
);
ListNode head2 =
new
ListNode(
4
);
head2.next =
new
ListNode(
11
);
head2.next.next =
new
ListNode(
8
);
head2.next.next.next =
new
ListNode(
2
);
head2.next.next.next.next =
new
ListNode(
5
);
head2.next.next.next.next.next =
new
ListNode(
2
);
head2.next.next.next.next.next.next =
new
ListNode(
5
);
head2.next.next.next.next.next.next.next =
new
ListNode(
4
);
int
k1 =
3
;
int
k2 =
9
;
ListNode result1 = findMinimumSublist(head1, k1);
ListNode result2 = findMinimumSublist(head2, k2);
System.out.print(
"Output 1: "
);
printList(result1);
System.out.print(
"Output 2: "
);
printList(result2);
}
}