public class LinkedList {
private Node head = null; //new Node();
public int listLength() {
int cnt = 0;
for (Node t = this.head; t != null; t = t.next) {
cnt++;
}
return cnt;
}
public void insertNode(int dat, int pos){
Node t = this.head;
Node prev = null;
for(int i=0; i<pos && t != null; i++, t=t.next)
prev = t;
Node p = new Node(dat);
p.next = prev.next;
prev.next = p;
}
public void printList() {
for (Node t = this.head; t != null; t = t.next) {
System.out.print(t.data + " ");
}
System.out.println();
}
public void reverseList() {
Node nxt = this.head;
Node prev = null;
while (nxt != null) {
Node tmp = nxt.next;
nxt.next = prev;
prev = nxt;
nxt = tmp;
}
this.head = prev;
}
public void addNode(int dat) {
Node p = new Node(dat);
Node t = this.head;
if (this.head == null) {
this.head = p;
} else {
while (t.next != null) {
t = t.next;
}
t.next = p;
}
}
public void deleteNode(int dat) {
Node t = this.head;
Node prev = t;
while (t != null) {
if (t.data == dat) {
prev.next = t.next;
}
prev = t;
t = t.next;
}
}
public void sortList() {
Node t = this.head;
for (; t != null; t = t.next) {
for (Node r = t.next; r != null; r = r.next) {
if (t.data > r.data) {
int temp = t.data;
t.data = r.data;
r.data = temp;
}
}
}
}
public static void main(String args[]) {
LinkedList ll = new LinkedList();
ll.addNode(10);
ll.addNode(15);
ll.addNode(18);
ll.addNode(1);
ll.addNode(20);
ll.addNode(3);
ll.addNode(7);
ll.printList();
System.out.println("Length: " + ll.listLength());
ll.reverseList();
ll.printList();
ll.sortList();
ll.printList();
ll.deleteNode(18);
ll.deleteNode(3);
ll.printList();
ll.insertNode(3, 3);
ll.insertNode(21, 5);
ll.insertNode(18, 7);
ll.printList();
}
}