Thursday, 18 February 2016

Make Linked List in Java (Class Composition Example) without using built-in Class


LinkNode.java
  
   

package my.kkc.LinkedList;

public class LinkNode {
    private int no;
    private String name;
    public LinkNode next;

    public LinkNode(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

  
LinkList.java
  
   
package my.kkc.LinkedList;

public class LinkList {

    private LinkNode first, last;

    public void insert(LinkNode linkNode) {
        if(first == null) {
            first = last = linkNode;
        } else {
            last.next = linkNode;
            last = linkNode;
        }
    }

    public void print() {
        LinkNode temp = first;
        while (temp!=null) {
            System.out.println(temp.getName()+" | "+temp.getNo());
            temp = temp.next;
        }
    }

    public LinkNode delete() {
        LinkNode temp = first;
        first = first.next;
        return temp;
    }
}

  
Main.java
  
   

package my.kkc.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkList linkList = new LinkList();

        linkList.insert(new LinkNode(121,"Midft"));
        linkList.insert(new LinkNode(122,"Midft"));
        linkList.insert(new LinkNode(123,"Midft"));

        linkList.print();
        linkList.delete();
        linkList.print();
    }
}
 
  

No comments:

Post a Comment