linked list
/**
* Linkedlist
*/
public class Linkedlist {
public static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public static Node head;
public static Node tail;
public void addFirst(int data) {
// step-1
// CREATE NEW NODE
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
return;
}
// step-2
// newnode next=head
newNode.next = head;
// step-3
// head=newNode
head = newNode;
}
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
}
tail.next = newNode;
tail = newNode;
}
public void print() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
Linkedlist ll = new Linkedlist();
ll.addFirst(1);
ll.addFirst(2);
ll.addLast(3);
ll.addLast(4);
;
ll.print();
}
}
Comments
Post a Comment