Linked List:
A linked list is a data structure where each element contain a pointer to the next element.
import java.util.Scanner;
class LLNode {
int key;
LLNode next;
LLNode(int key) {
this.key=key;
}
}
public class LL {
LLNode temp, first;
int size;
LL() {
temp=null;
first=null;
size=0;
}
public void insert(int key) {
LLNode data=new LLNode(key);
if(first==null) {
first=data;
temp=data;
}
else {
temp=first;
while(temp.next!=null) {
temp=temp.next;
}
temp.next=data;
}
size++;
}
public void remove(int key) {
if(size==0) {
System.out.println("\nEmpty LL");
return;
}
temp=first;
if(temp.key==key) {
first=first.next;
size--;
return;
}
else {
while(temp.next!=null){
if(temp.next.key==key) {
if(temp.next.next==null) {
temp.next=null;
size--;
return;
}
temp.next=temp.next.next;
size--;
return;
}
temp=temp.next;
}
}
System.out.println("\nElement Not Found");
}
public void disp() {
temp=first;
while(temp!=null) {
System.out.println(temp.key);
temp=temp.next;
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
LL ll=new LL();
while(true) {
System.out.print("\n1. Insert\n2. Remove\n3. Display\nCHOICE: ");
int ch=sc.nextInt();
switch(ch) {
case 1:
System.out.println("\nEnter A Number: ");
int num=sc.nextInt();
ll.insert(num);
break;
case 2:
System.out.println("\nEnter A Number: ");
num=sc.nextInt();
ll.remove(num);
break;
case 3:
ll.disp();
break;
default :
System.exit(0);
}
}
}
}
A linked list is a data structure where each element contain a pointer to the next element.
Sample Code (in Java) :
class LLNode {
int key;
LLNode next;
LLNode(int key) {
this.key=key;
}
}
public class LL {
LLNode temp, first;
int size;
LL() {
temp=null;
first=null;
size=0;
}
public void insert(int key) {
LLNode data=new LLNode(key);
if(first==null) {
first=data;
temp=data;
}
else {
temp=first;
while(temp.next!=null) {
temp=temp.next;
}
temp.next=data;
}
size++;
}
public void remove(int key) {
if(size==0) {
System.out.println("\nEmpty LL");
return;
}
temp=first;
if(temp.key==key) {
first=first.next;
size--;
return;
}
else {
while(temp.next!=null){
if(temp.next.key==key) {
if(temp.next.next==null) {
temp.next=null;
size--;
return;
}
temp.next=temp.next.next;
size--;
return;
}
temp=temp.next;
}
}
System.out.println("\nElement Not Found");
}
public void disp() {
temp=first;
while(temp!=null) {
System.out.println(temp.key);
temp=temp.next;
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
LL ll=new LL();
while(true) {
System.out.print("\n1. Insert\n2. Remove\n3. Display\nCHOICE: ");
int ch=sc.nextInt();
switch(ch) {
case 1:
System.out.println("\nEnter A Number: ");
int num=sc.nextInt();
ll.insert(num);
break;
case 2:
System.out.println("\nEnter A Number: ");
num=sc.nextInt();
ll.remove(num);
break;
case 3:
ll.disp();
break;
default :
System.exit(0);
}
}
}
}
No comments:
Post a Comment