File size: 2,566 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
package linklistapp;
public class LinkListApp {
public static void main(String[] args) {
LinkList x=new LinkList();
x.insertFirst(5);
x.insertFirst(9);
x.insertFirst(3);
x.insertFirst(7);
x.displayList();
x.delete(1);
x.displayList();
Node k=x.find(2);
k.displayNode();
}
}
class Node {
int data;
Node next;
Node(int item) {
this.data = item;
this.next = null;
}
void displayNode() {
System.out.print(this.data + " ");
}
}
class LinkList {
private Node head;
public LinkList() {//constructor
head = null;
}
public boolean isEmpty() {
return (this.head == null);
}
public void insertFirst(int i) {
Node newNode = new Node(i);
newNode.next = head;
head = newNode;
}
public Node deleteFirst() {
if (isEmpty()) {
System.out.println("List is empty");
return null;
}
Node temp = head;
head = head.next;
temp.next = null;
return temp;
}
public void displayList() {
if (isEmpty()) {
System.out.println("List is empty");
return;
}
Node current = head;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public Node find(int key) {//metion node location
Node current = head;
int count = 1;
while (current != null) {
if (count == key) {
Node temp=new Node(current.data);
return temp;
}
current = current.next;
count++;
}
System.out.println("Item not found");
return null;
}
public void delete(int key) {
if (isEmpty()) {
System.out.println("List is empty");
return;
}
Node current = head;
Node previous = head;
int count = 1;
while (current != null) {
if (count == key) {
if (count == 1) {
head = head.next;
} else {
previous.next = current.next;
}
System.out.println("Item deleted");
return;
}
previous = current;
current = current.next;
count++;
}
System.out.println("Item not avaliable");
}
} |