/* Program written by Luis Gallego
*
*/
public class LinkedList {
Node head;
public void insert(String item) {
Node curr = head;
Node prev = head;
// If the list is empty, then execute this if statement
if (head == null)
head = new Node(item);
else {
while (curr != null && curr.data.compareTo(item) < 0) {
prev = curr;
curr = curr.next;
}
// add beginning
if (head == curr) {
Node newNode = new Node(item);
newNode.next = head;
head = newNode;
}
else if (curr == null) {
Node newNode = new Node(item);
prev.next = newNode;
}
else {
Node newNode = new Node(item);
prev.next = newNode;
newNode.next = curr;
}
}
}
public void delete(String item) {
Node curr = head;
Node prev = head;
// if the list is empty
if (curr == null) {
System.out.println("The list is empty!");
}
// if the head node is the item we want to delete
else if (curr.data.compareTo(item) == 0) {
head = head.next;
}
// general case if node is in the middle
else {
while (curr != null && curr.data.compareTo(item) != 0) {
prev = curr;
curr = curr.next;
}
if (curr == null) {
System.out.println("Item not found!");
} else {
prev.next = curr.next;
}
}
}
// method to print the list
public void print() {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println(); // move cursor
}
public static void main(String[] args) {
LinkedList myList = new LinkedList();
myList.print();
myList.insert("apple");
myList.print();
myList.insert("orange");
myList.print();
myList.insert("kiwi");
myList.print();
myList.insert("tangerine");
myList.print();
myList.insert("strawberry");
myList.print();
myList.delete("apple");
myList.print();
myList.delete("strawberry");
myList.print();
myList.delete("tangerine");
myList.print();
myList.insert("apple");
myList.print();
myList.delete("tangerine");
myList.print();
myList.delete("apple");
myList.print();
myList.delete("tangerine");
myList.print();
myList.delete("apple");
myList.print();
myList.delete("kiwi");
myList.print();
myList.delete("orange");
myList.print();
myList.delete("strawberry");
myList.print();
myList.insert("job-well-done");
myList.print();
}
}
syntax highlighting by pygments via the monkey pygment web app
Node Class:
/* Program written by Luis Gallego
*/
public class Node {
String data;
Node next;
public Node(String data){
this.data = data;
next = null;
}
// set and get methods
public Node(String data, Node nextNode){
this.data = data;
next = nextNode;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
// Overloaded toString method
public String toString(){
return data;
}
}
syntax highlighting by pygments via the monkey pygment web app
No comments:
Post a Comment