Files
cs-109-intro-to-programming/src/CircularLinkedList.java

94 lines
2.1 KiB
Java

public class CircularLinkedList {
public int size = 0;
public Node head = null;
public Node tail = null;
public static void main(String[] args) {
CircularLinkedList myList = new CircularLinkedList();
myList.addNodeToHead(75);
myList.addNodeToHead(50);
myList.addNodeToHead(25);
myList.print();
myList.addNodeToTail(100);
myList.print();
myList.rotateElement();
myList.print();
myList.deleteNodeFromTail();
myList.print();
myList.deleteNodeFromHead();
myList.print();
}
// Add a new Node at the start of the Linked List
public void addNodeToHead(int element) {
Node n = new Node(element);
if (size == 0) {
head = n;
tail = n;
} else {
n.next = head;
head = n;
tail.next = head;
}
size++;
}
// Add a new Node to the Tail of the Linked List
public void addNodeToTail(int element) {
if (size == 0) {
addNodeToHead(element);
} else {
Node n = new Node(element);
tail.next = n;
tail = n;
tail.next = head;
size++;
}
}
public void rotateElement() {
System.out.println("Rotating!");
tail = head;
head = head.next;
}
public void deleteNodeFromTail() {
System.out.println("\nDeleting Node " + tail.element + " from Tail");
if (tail.next == tail) {
tail = null;
}
Node newTail = tail;
while (newTail.next != tail) {
newTail = newTail.next;
}
newTail.next = tail.next;
tail = newTail;
}
public void deleteNodeFromHead() {
head = head.next;
tail.next = head;
size--;
}
public void print() {
System.out.println("The List so far: ");
Node temp = head;
do {
System.out.print(" " + temp.element);
temp = temp.next;
} while (temp != head);
System.out.println();
}
}