class Node{ int data=0; Node next; Node(int data){ this.data =data; this.next=null; } int value(){ return data; } void show(){ System.out.print(" (" + data + ")"); } } |
The LinkList Class |
public class LinkList { // an ordered list private Node start=null; void add(int data){ if(start==null) start = new Node(data); // add as only node in list else insert(data); // insert in the order } void add(int data[]){ for(int i=0; i < data.length ; i++) add(data[i]); } void show(){ Node temp=start; while(temp != null){ temp.show(); temp=temp.next; } System.out.println(); } boolean remove(int data){ Node temp=start,x; if(temp==null) { System.out.println("The list is empty/not exisitng"); return false; } if(temp.data == data){ // if first item start = temp.next; temp.show(); return true; } while(temp.next != null){ if(temp.next.data == data){ x=temp.next; //x=temp.next is the node to delete temp.next=x.next; // bypass x x.show(); x=null; // remove x return true; } temp=temp.next; } System.out.print("\nItem not found : " + data); return false; } void remove(int data[]){ // remove an array of items for(int i=0; i < data.length ; i++) remove(data[i]); } private void insert(int data){ Node t=start, node=new Node(data); if (t.value() > data){ // insert as first item node.next=t; start=node; return; } else{ while(t.next != null){ if(t.value()== data){ // check for duplicate System.out.println("duplicate ingnored : " + data); return; } if(t.next.value() > data){ // if found a greater value insert before it node.next=t.next; t.next=node; return; } t=t.next; } t.next=node; //set as the last item } } } |
The Driver Class - Main |
public class Main { public static void main(String[] args) { LinkList ll=new LinkList(); ll.add(2546); ll.add(777); ll.add(666); ll.add(66); ll.add(6); int xx[]={1,2,3,4,5,6,66,77,777,7,99,88,55,44,33,22}; int yy[]={4,5,6,7,77}; ll.add(xx); ll.show(); ll.remove(xx); ll.remove(yy); ll.show(); } } |
The Output |
duplicate ingnored : 6 duplicate ingnored : 66 duplicate ingnored : 777 (1)(2)(3)(4)(5)(6)(7)(22)(33)(44)(55)(66)(77)(88)(99)(666)(777)(2546) (1)(2)(3)(4)(5)(6)(66)(77)(777)(7)(99)(88)(55)(44)(33)(22) Item not found : 4 Item not found : 5 Item not found : 6 Item not found : 7 |
Java, JSP, Servelet, C, C++, VC++, VB6, VB.NET, C#.NET, ASP.NET, HTML, VB/JavaScript, PHP, Python and Django
Pages
- Creative Writing Workshop at Hill Blooms School
- My Photos
- Sorting in C
- C and C++
- VB6 File Handling
- Hardware - Trouble Shooting
- VIJEESH
- Linked List in Java
- Queue in Java using Array Data Structure
- The Queue Class
- English Grammar by My Teacher.
- C tips and Recursion
- Abstract Class
- Dynamic Polimorphism (Abastract Class) in C++
Linked List in Java
Subscribe to:
Posts (Atom)