Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. //Class Node
  2. public class Node {
  3.     public int data;
  4.     public Node next;
  5.    
  6.     public Node(int d){
  7.         data=d;
  8.         next=null;
  9.     }
  10.    
  11. }
  12.  
  13. //Class LinkedList
  14. public class LinkedList {
  15.    
  16.     Node head;
  17.    
  18.    
  19.     public void push(int new_data){
  20.         if(head==null){
  21.             head=new Node(new_data);
  22.             return;
  23.         }
  24.        
  25.         Node newNode=new Node(new_data);
  26.         newNode.next=head;
  27.         head=newNode;
  28.     }
  29.    
  30.     public int getCount(){
  31.         if(head==null) return 0;
  32.        
  33.         Node temp=head;
  34.        
  35.         int count=0;
  36.        
  37.         while(temp!=null){
  38.        
  39.             //System.out.println(temp.data);
  40.             count++;
  41.             temp=temp.next;
  42.            
  43.         }
  44.        
  45.         return count;    
  46.     }
  47.    
  48.     //Bonus task
  49.     public Node getMiddleNode() throws Exception{
  50.        
  51.         if(head==null) throw new Exception("The list is empty.");
  52.        
  53.         if(head.next==null) return head;
  54.        
  55.        
  56.         Node temp1=head;
  57.         Node temp2=head;
  58.        
  59.         while(temp2!=null){
  60.             if(temp2.next==null) return temp1;
  61.            
  62.             temp1=temp1.next;
  63.             temp2=temp2.next.next;
  64.        
  65.         }
  66.        
  67.         return temp1;
  68.    
  69.     }
  70.    
  71.     public static void main(String[] args){
  72.    
  73.         LinkedList llist=new LinkedList();
  74.         llist.push(1);
  75.         llist.push(3);
  76.         llist.push(1);
  77.         llist.push(2);
  78.         llist.push(1);
  79.         llist.push(10);
  80.         llist.push(12);
  81.        
  82.        
  83.         System.out.println("Count of nodes is: "+ llist.getCount());
  84.        
  85.         try {
  86.             Node node=llist.getMiddleNode();
  87.             System.out.println("Middle node is: " +node.data);
  88.         } catch (Exception ex) {
  89.             System.out.println(ex.getMessage());
  90.         }
  91.    
  92.     }
  93.    
  94.    
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement