all method of link list in java

link list

link list is a dynamic data structure so in link list we can add element in run time.here we will implement how to implement

  • node link list

class Node{
public int data;//data 
public Node next;//next
Node()//constructor
{
data=0;
next=null;
}

Node(int data,Node next)//constructor
{
 this.data=data;
 this.next=next;
}
//set data
public void setData(int val)
{
 data=val;
}

public Node setNext(Node n) {return next=n;}

public int getData() {int val=data;return val;}
public Node getNext() { return next;}
public String toString()
{
     return "data="+data;
}
}//end of node

  • is link list is empty. 
public boolean isEmpty()
 {
  return start==null;
 }

  • add element at first position of link list.
//insert at first position.
 public void insertAtFirst(int val) 
 { 
  Node tt=new Node(val,start);
  start=tt;
  size++;
    }
 //insert at last
 public void insertAtLast(int val) {
  Node n,t;
  t=start;
  n=new Node(val,null);
  if(isEmpty())
  {
   start=n;
  }
  else
  {
   
    while(t.getNext()!=null)
    { 
     t=t.getNext();
    }
    t.setNext(n);
  }
  size++; 
 }
 

  • add element at last position.

//insert at position
   public void insertAtPosition(int val,int pos)
  {
  
   
   if(pos==1)
   {
    insertAtFirst(val);
    
   }
   else if(pos==size+1)
   {
    insertAtLast(val);
   }
   else if(pos>1&&pos<=size)
   {
    Node t,n;
    n=new Node(val,null);
    t=start;
    for(int i=1;i

  • delete node from first position.
 //delete first  
  public void deleteFirst()
  {
   if(isEmpty())
   {
    System.out.println("List is empty");
   }
   else
   {
    start=start.getNext();
    size--;
   }
  }

  • delete node from last.
//delete last
  public void deleteLast()
  {
   Node t;
   t=start;   
   for(int i=1;i

  • view link list.
public void viewList() {
 Node temp;
  if(isEmpty())
  {
   System.out.println("List is empty.");
  }
  else 
  {
   temp=start;
   for(int i=1;i<=size;i++) 
   {
    System.out.println(temp.getData());
   temp=temp.getNext();
       }
        }
                 }//end method view list

Comments

Popular posts from this blog

A publishing company that markets both book and audio-cassette in java. (Solution)

Create a class named Movie that can be used with your video rental business in java

informed Search and Uninformed Search