-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinkedListSplit.java
30 lines (25 loc) · 982 Bytes
/
LinkedListSplit.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
import java.util.LinkedList;
public class LinkedListSplit {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
// Split the LinkedList into two halves
LinkedList<Integer> firstHalf = new LinkedList<>();
LinkedList<Integer> secondHalf = new LinkedList<>();
int middleIndex = linkedList.size() / 2;
for (int i = 0; i < middleIndex; i++) {
firstHalf.add(linkedList.get(i));
}
for (int i = middleIndex; i < linkedList.size(); i++) {
secondHalf.add(linkedList.get(i));
}
// Print the two halves of the LinkedList
System.out.println("First Half: " + firstHalf);
System.out.println("Second Half: " + secondHalf);
}
}