Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LinkedList<T> implements ListInterface<T> {
- Node<T> head;
- int size;
- // constructor
- public class Node<T> {
- public T data;
- public Node<T> next;
- public Node (T data, Node<T> next) {
- this.data = data;
- this.next = next;
- }
- }
- //add
- public void add(T data, int index) {
- if (size == 0 || index == 0) { // if there isn't an existing list create one and set head position
- head = new Node<T>(data, head);
- }
- else { // loops the list starting from head, at an empty spot add the object
- Node<T> current = head;
- while(index > 1) { // increment pointer until desired index is reached
- current = current.next;
- index--;
- }
- current.next = new Node<T>(data, current.next);
- }
- size++;
- }
- // get
- public T get(int index) {
- Node<T> current = head;
- while(index > 0) {
- if (current == null) { // if nothing exists at this index, throw exception
- throw new ListException("Cannot get item/DNE.");
- }
- // increment pointer
- current = current.next;
- index--;
- }
- return current.data;
- }
- // remove
- public void remove(int index) {
- Node<T> current = head;
- if (current == null)// if there isn't an object in the index, throw exception
- throw new ListException("Cannot remove item/DNE.");
- if(index == 0) { // If you want to remove at the beginning, we need to reassign the head
- head = head.next;
- }
- else {
- while (index > 1) { // loop to the desired index
- current = current.next;
- index--;
- }
- // reassigns the index, removed item is detached and gets garbage collected.
- current.next = current.next.next;
- }
- size--;
- }
- // size
- public int size() {
- return size;
- }
- // Appends contents of list to a stringbuffer and returns them
- public String toString() {
- Node<T> node = head;
- StringBuffer str = new StringBuffer();
- while (node != null) {
- str.append(node.data.toString() + " ");
- node = node.next;
- }
- return str.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement