Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package opgave1;
- public class SingleLinked {
- private Node<String> first;
- public SingleLinked() {
- this.first = null;
- }
- private static class Node<T> {
- private T data;
- private Node<T> next;
- public Node(T data) {
- this.data = data;
- this.next = null;
- }
- }
- /**
- * Adds the element to the list. The list is still sorted after the element is
- * added.
- */
- public void add(String element) {
- Node<String> newNode = new Node<>(element);
- if (this.first == null || this.first.data.compareTo(element) >= 0) {
- newNode.next = this.first;
- this.first = newNode;
- } else {
- Node<String> current = this.first;
- while (current.next != null && current.next.data.compareTo(element) < 0) {
- current = current.next;
- }
- newNode.next = current.next;
- current.next = newNode;
- }
- }
- /**
- * Removes the first instance of the element from the list. The list is still
- * sorted after the element is removed. Returns true, if the element was
- * removed, otherwise false.
- */
- public boolean remove(String element) {
- if (first == null) {
- return false;
- }
- if (first.data.equals(element)) {
- first = first.next;
- return true;
- }
- Node<String> n = first;
- while (n.next != null) {
- if (n.next.data.equals(element)) {
- n.next = n.next.next;
- return true;
- }
- n = n.next;
- }
- return false;
- }
- /**
- * Prints all elements in alphabetical order.
- */
- public void printElements() {
- Node<String> n = first;
- while (n != null) {
- System.out.println(n.data);
- n = n.next;
- }
- }
- /**
- * Returns the count of elements in the list.
- */
- public int count() {
- if (first == null) {
- return 0;
- }
- int count = 1;
- Node<String> n = first;
- while (n.next != null) {
- n = n.next;
- count++;
- }
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement