Advertisement
farhansadaf

Problem 3

Jul 20th, 2020
1,359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. import java.util.LinkedList;
  2.  
  3. /**
  4.  * PROBLEM *
  5.  Write a program to insert 100 to a dynamic list.
  6.  Now start a loop from 1 to 10.
  7.  If the iteration number is odd add the number to the top of the list.
  8.  And if the iteration number is even, add the number to the bottom of the list.
  9.  Read the list from top to bottom and output the list.
  10.  Choose LinkedList for the implementation.
  11.  [Hint: Output = 9 7 5 3 1 100 2 4 6 8]
  12. **/
  13.  
  14. public class Problem3 {
  15.     public static void main(String[] args) {
  16.         LinkedList<Integer> linkedList = new LinkedList();
  17.        
  18.         // Inserting 100 to linked list.
  19.         linkedList.add(100);
  20.        
  21.         // Loop through 1,..., 10
  22.         for (int v = 1; v < 10; v++) {
  23.            
  24.             // If v is even
  25.             if (v % 2 == 0) {
  26.                 // Add v to the bottom of the list.
  27.                 linkedList.addLast(v);
  28.             }
  29.             // If v is odd (Not even)
  30.             else {
  31.                 // Add v to the top of the list.
  32.                 linkedList.addFirst(v);
  33.             }
  34.         }
  35.        
  36.         // Reading the list from top to bottom and output the list.
  37.         System.out.print("Output = ");
  38.         for (Integer v : linkedList) {
  39.             System.out.print(v + " ");
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement