Skip to main content

Deleting a Node by passing data in LInkedList

Deleting a Node by passing data in LInkedList:-

The node can be deleted by passing the data value in a function.Here we have three pointers one to traverse the list other to point current node and third one to point previous of current node.



//deleting a given key
 public Node deleteKeyNode(Node head,int key)
 {
  //traverse pointer
  Node temp=head;
  //previous pointer
  Node prevtemp=temp;
  
  while(temp!=null)
  {
   //when key is at head position
   if(key==head.data)
   {
    head=head.next;
    System.out.println("head is deleted");
    return head;
   }
   
   //when key is at any position other than head
   if(temp.data==key)
   {
    prevtemp.next=temp.next;
    temp.next=null;
    temp=prevtemp; 
   }
   prevtemp=temp;
   temp=temp.next;
  }
  return head;
 }

Comments

.

Popular posts from this blog

How to design a Node in Tree?

How to design a Node in Tree?

There are three main components of a tree in a node.

 1) Integer holding data.
2) Left pointer holding node in a left subtree.
3) Right pointer holding node in a right subtree.

The following design is having data of int type and left,right pointers of a node to the subtrees.


package com.BST;publicclassNode{int data; Node left; Node right;/** * @return the data */publicNode(int data){this.left=null;this.right=null;this.data=data;}publicintgetData(){return data;}/** * @param data the data to set */publicvoidsetData(int data){this.data= data;}/** * @return the left */public Node getLeft(){return left;}/** * @param left the left to set */publicvoidsetLeft(Node left){this.left= left;}/** * @return the right */public Node getRight(){return right;}/** * @param right the right to set */publicvoidsetRight(Node right){this.right= right;}/* (non-Javadoc) * @see java.lang.Object#toString() */@Overridepublic String toString(){return"Node [data=&quo…

basics of java in layman term for beginner

Basics of java in layman term for beginner
What is an object ?

object is a real world entity.

Object is an instance of the class.It means something that is alive. Let us take an example of CAR:-

concept of a car is class. I mean we all know that it is having four tyres , one engine , four doors , a seat e.t.c. but we can't do anything just by the concept we need real Car to perform operations on it . This real car is what we call is an object.


Explain about main()method in java ?

main() method is an entry point of a program.
public static void main(String[] args)

Why main()method is public, static and void in java ?

public: It can be accessed from anywhere.
static: no class object need to call this method.
void: it is not returning anything in back.

What is JIT compiler ?

JIT is just in time compiler.JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usu…