Skip to content

Instantly share code, notes, and snippets.

@jananpatel2002
Last active December 1, 2021 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jananpatel2002/21da5093fe288ba63163d62cd34643d5 to your computer and use it in GitHub Desktop.
Save jananpatel2002/21da5093fe288ba63163d62cd34643d5 to your computer and use it in GitHub Desktop.
package chapter24;
/*
* Name: Janan Patel
* Date: 11/29/2021
* Course Number: CSC-220
* Course Name: Data Structures
* Problem Number: 10
* Email: jkpatel2001@student.stcc.edu
* My Linked List class with all main methods.
*/
public class MyLinkedList<E> implements MyList<E> {
private static class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this(data, null);
}
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
private Node<E> head, tail;
private int size = 0; // Number of datas in the list
/** Create an empty list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
for (int i = 0; i < objects.length; i++)
this.add(objects[i]);
}
/** Return the head data in the list */
public E getFirst() {
if (head != null) {
return head.data;
}
return null;
}
/** Return the last data in the list */
public E getLast() {
if (tail != null) {
return tail.data;
}
return null;
}
/** Add an data to the beginning of the list */
public void addFirst(E e) {
Node<E> newNode = new Node<>(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an data to the end of the list */
public void addLast(E e) {
Node<E> newNode = new Node<>(e); // Create a new for data e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
} else {
tail.next = newNode; // Link the new with the last node
tail = newNode; // tail now points to the last node
}
size++; // Increase size
}
@Override /**
* Add a new data at the specified index in this list. The index of the head
* data is 0
*/
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
} else if (index >= size) {
addLast(e);
} else {
Node<E> current = head;
Node<E> prev = null;
for (int i = 0; i < index; i++) {
prev = current;
current = current.next;
}
Node<E> newNode = new Node<>(e);
prev.next = newNode;
newNode.next = current;
size++;
}
}
/**
* Remove the head node and return the object that is contained in the removed
* node.
*/
public E removeFirst() {
if (size == 0) {
return null;
} else {
E temp = head.data;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return temp;
}
}
/**
* Remove the last node and return the object that is contained in the removed
* node.
*/
public E removeLast() {
if (size == 0) {
return null;
} else if (size == 1) {
E temp = head.data;
head = tail = null;
size = 0;
return temp;
} else {
Node<E> current = head;
for (int i = 0; i < size - 2; i++) {
current = current.next;
}
E temp = tail.data;
tail = current;
tail.next = null;
size--;
return temp;
}
}
@Override /**
* Remove the data at the specified position in this list. Return the data that
* was removed from the list.
*/
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
} else if (index == 0) {
return removeFirst();
} else if (index == size - 1) {
return removeLast();
} else {
Node<E> current = head;
Node<E> prev = null;
for (int i = 0; i < index; i++) {
prev = current;
current = current.next;
}
prev.next = current.next;
size--;
return current.data;
}
}
@Override /** Override toString() to return datas in the list */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node<E> current = head;
for (int i = 0; i < size; i++) {
result.append(current.data);
current = current.next;
if (current != null) {
result.append(", "); // Separate two datas with a comma
} else {
result.append("]"); // Insert the closing ] in the string
}
}
return result.toString();
}
@Override /** Clear the list */
public void clear() {
size = 0;
head = tail = null;
}
@Override /** Return true if this list contains the data e */
public boolean contains(Object e) {
return indexOf(e) != -1;
}
@Override /** Return the data at the specified index */
public E get(int index) {
int currentIndex = 0;
Node<E> current = head;
while (currentIndex != index) {
current = current.next;
currentIndex++;
}
return current.data;
}
@Override /**
* Return the index of the head matching data in this list. Return -1 if no
* match.
*/
public int indexOf(Object e) {
int index = 0;
Node<E> current = head;
while (current != null) {
if (current.data.equals(e))
return index;
index++;
current = current.next;
}
return -1;
}
@Override /**
* Return the index of the last matching data in this list. Return -1 if no
* match.
*/
public int lastIndexOf(E e) {
int index = 0;
int count = -1;
Node<E> currentIndex = head;
while (currentIndex.next != null) {
if (currentIndex.data.equals(e)) {
count = index;
}
index++;
currentIndex = currentIndex.next;
if (currentIndex.data.equals(e)) {
count = index;
}
}
return count;
}
@Override /**
* Replace the data at the specified position in this list with the specified
* data.
*/
public E set(int index, E e) {
remove(index);
add(index,e);
return e;
}
@Override /** Return the number of datas in this list */
public int size() {
return size;
}
@Override /** Override iterator() defined in Iterable */
public java.util.Iterator<E> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements java.util.Iterator<E> {
private Node<E> current = head; // Current index
@Override
public boolean hasNext() {
return (current != null);
}
@Override
public E next() {
E e = current.data;
current = current.next;
return e;
}
@Override
public void remove() {
// Left as an exercise
}
}
}
/*
* Name: Janan Patel
* Date: 11/29/2021
* Course Number: CSC-220
* Course Name: Data Structures
* Problem Number: 10
* Email: jkpatel2001@student.stcc.edu
* My List
*/
package chapter24;
import java.util.Collection;
public interface MyList<E> extends Collection<E> {
/** Add a new element at the specified index in this list */
public void add(int index, E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(Object e);
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public E remove(int index);
/** Replace the element at the specified position in this list
* with the specified element and returns the new set. */
public E set(int index, E e);
@Override /** Add a new element at the end of this list */
public default boolean add(E e) {
add(size(), e);
return true;
}
@Override /** Return true if this list contains no elements */
public default boolean isEmpty() {
return size() == 0;
}
@Override /** Remove the first occurrence of the element e
* from this list. Shift any subsequent elements to the left.
* Return true if the element is removed. */
public default boolean remove(Object e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
}
else
return false;
}
@Override
public default boolean containsAll(Collection<?> c) {
// Left as an exercise
return true;
}
@Override
public default boolean addAll(Collection<? extends E> c) {
// Left as an exercise
return true;
}
@Override
public default boolean removeAll(Collection<?> c) {
// Left as an exercise
return true;
}
@Override
public default boolean retainAll(Collection<?> c) {
// Left as an exercise
return true;
}
@Override
public default Object[] toArray() {
// Left as an exercise
return null;
}
@Override
public default <T> T[] toArray(T[] array) {
// Left as an exercise
return null;
}
}
/*
* Name: Janan Patel
* Date: 11/29/2021
* Course Number: CSC-220
* Course Name: Data Structures
* Problem Number: 10
* Email: jkpatel2001@student.stcc.edu
* Test driver for Linked Lists
*/
package chapter24;
import java.util.Scanner;
public class TestMyLinkedList {
private final static String TITLE = "The My Linked List Program ";
private final static String CONTINUE_PROMPT = "Do this again? [y/N] ";
// **********************************************
// Put as many methods you need here
private static String getFirstCharacter(String str) {
str = str.trim().toUpperCase();
return str.isEmpty() ? "" : str.substring(0, 1);
}
// **********************************************
@SuppressWarnings("unchecked")
private static void process(Scanner sc, String args[]) {
@SuppressWarnings("rawtypes")
MyLinkedList list = new MyLinkedList<>();
System.out.print(
"Select the following: [A]DD, [R]EMOVE, [P]RINT, [I]NDEX OF, [C]ONTAINS, [G]ET, [L]AST INDEX, [S]ET, [Q]UIT ");
String x = getFirstCharacter(sc.nextLine());
while (!x.equals("Q")) {
switch (x) {
case "A": {
System.out.println("What would you like to add:");
var addingValue = sc.nextLine();
list.add(addingValue);
break;
}
case "P": {
System.out.println(list);
break;
}
case "R": {
System.out.println("Enter the value that you would like to remove: ");
var removedValue = sc.nextLine();
if (list.contains(removedValue)) {
list.remove(removedValue);
System.out.println(removedValue + " Has been removed");
break;
}
System.out.println("This value doesn't exist in the List");
break;
}
case "I": {
System.out.println("What value would you like to find the index of ? ");
var indexOf = sc.nextLine();
System.out.println("The Index of " + indexOf + " = " + list.indexOf(indexOf));
break;
}
case "C": {
System.out.println("What value are you trying to find ? ");
var data2 = sc.nextLine();
System.out.println(data2 + " is in the Linked List = " + list.contains(data2));
break;
}
case "G": {
System.out.println("What is the index of the value that you are trying to get? ");
int indexOfValue = sc.nextInt();
if (indexOfValue < 0) {
System.out.println("Out of bounds, use a value above 0");
break;
}
System.out.println("The value at index " + indexOfValue + " = " + list.get(indexOfValue));
break;
}
case "L": {
System.out.println("What value are you trying to find the last index for?");
var lastIndexValue = sc.nextLine();
System.out.println(
"The last occurence of " + lastIndexValue + " is at index " + list.lastIndexOf(lastIndexValue));
break;
}
case "S": {
System.out.println(
"Remove a value and replace it: Enter the index and then enter the value with a space in between. ALL IN ONE LINE.");
int index = sc.nextInt();
var value = sc.nextLine().trim();
list.set(index, value);
break;
}
default:
System.out.println("Invalid letter/word");
break;
}
System.out.println(
"Select the following: [A]DD, [R]EMOVE, [P]RINT, [I]NDEX OF, [C]ONTAINS, [G]ET, [L]AST INDEX, [S]ET, [Q]UIT ");
x = getFirstCharacter(sc.nextLine());
}
}
// **********************************************
// Do not change the doThisAgain method
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
// **********************************************
// Do not change the main method
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment