Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- /**
- * PROBLEM *
- Write a program to insert 100 to a dynamic list.
- Now start a loop from 1 to 10.
- If the iteration number is odd add the number to the top of the list.
- And if the iteration number is even, add the number to the bottom of the list.
- Read the list from top to bottom and output the list.
- Choose LinkedList for the implementation.
- [Hint: Output = 9 7 5 3 1 100 2 4 6 8]
- **/
- public class Problem3 {
- public static void main(String[] args) {
- LinkedList<Integer> linkedList = new LinkedList();
- // Inserting 100 to linked list.
- linkedList.add(100);
- // Loop through 1,..., 10
- for (int v = 1; v < 10; v++) {
- // If v is even
- if (v % 2 == 0) {
- // Add v to the bottom of the list.
- linkedList.addLast(v);
- }
- // If v is odd (Not even)
- else {
- // Add v to the top of the list.
- linkedList.addFirst(v);
- }
- }
- // Reading the list from top to bottom and output the list.
- System.out.print("Output = ");
- for (Integer v : linkedList) {
- System.out.print(v + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement