Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Class Node
- public class Node {
- public int data;
- public Node next;
- public Node(int d){
- data=d;
- next=null;
- }
- }
- //Class LinkedList
- public class LinkedList {
- Node head;
- public void push(int new_data){
- if(head==null){
- head=new Node(new_data);
- return;
- }
- Node newNode=new Node(new_data);
- newNode.next=head;
- head=newNode;
- }
- public int getCount(){
- if(head==null) return 0;
- Node temp=head;
- int count=0;
- while(temp!=null){
- //System.out.println(temp.data);
- count++;
- temp=temp.next;
- }
- return count;
- }
- //Bonus task
- public Node getMiddleNode() throws Exception{
- if(head==null) throw new Exception("The list is empty.");
- if(head.next==null) return head;
- Node temp1=head;
- Node temp2=head;
- while(temp2!=null){
- if(temp2.next==null) return temp1;
- temp1=temp1.next;
- temp2=temp2.next.next;
- }
- return temp1;
- }
- public static void main(String[] args){
- LinkedList llist=new LinkedList();
- llist.push(1);
- llist.push(3);
- llist.push(1);
- llist.push(2);
- llist.push(1);
- llist.push(10);
- llist.push(12);
- System.out.println("Count of nodes is: "+ llist.getCount());
- try {
- Node node=llist.getMiddleNode();
- System.out.println("Middle node is: " +node.data);
- } catch (Exception ex) {
- System.out.println(ex.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement