Creating A Linked List In Java Using Generics - java

I've looked through the site and can't find anything that is at least comparable to what I'm doing (please do not link any stackoverflow responses or questions I've been looking for an hour), so I've decided to ask this question. I'm trying to create a linked list (not using libraries of any kind) that uses generics, here is all the relevant code.
public class LList<T>
{
MyNode<T> head = null;
MyNode<T> tail = null;
MyNode<T> temp = null;
int count = 0;;
Scanner scan = new Scanner(System.in);
//puts a new value at the edn of the list
public void add(T i)
{
if(head == null)
{
head = new MyNode<T>();
head.data = i;
head.next = tail;
tail = head;
}
else
{
tail.next = new MyNode<T>();
tail = tail.next;
tail.data = i;
}
count ++;
}
//inserts a new value at a given index
public void insert(int index, T item)
{
if(index == size())
{
add(item);
}
else if(index == 0)
{
MyNode<T> temp = new MyNode<T>();
temp.data = item;
temp.next = head;
head.previous = temp;
head = temp;
count++;
}
temp = head;
for(int i = 0; i < index-1; i++)
{
temp = temp.next;
MyNode<T> myNode = new MyNode<T>();
myNode.data = item;
myNode.next = temp.next;
temp.next = myNode;
count++;
}
}
//returns the number of values in the list
public int size()
{
return count;
}
//returns the value at a given index
public T get(int index)
{
if(head == null || index > count -1)
{
return null;
}
if(index < 0 || index >= count)
{
System.out.println("This does not exist");
}
MyNode<T> p = head;
int size = 0;
while(size < index && p.next != null)
{
p = p.next;
size++;
}
if(count != index)
{
return null;
}
else
{
return p.data;
}
}
//removes the returns the first value in the list
public T remove()
{
head = head.next;
head.previous = null;
count--;
return (T) head;
}
//removes and returns the value at a given index
public T removeAt(T elem)
{
temp = head;
MyNode<T> two = null;
if(head.data.equals(elem))
{
head = head.next;
head.previous = null;
count--;
return elem;
}
else if(tail.data.equals(elem))
{
tail = tail.previous;
tail.next = null;
count--;
return elem;
}
while(temp != null && !temp.data.equals(elem))
{
two = temp;
temp = temp.next;
}
if(temp == null)
{
return null;
}
two.next = temp.next;
T spare = temp.data;
temp = null;
count--;
return spare;
}
//removes and returns the last value in the list
public T removeLast()
{
temp = tail;
tail = tail.previous;
temp = null;
count--;
return (T) tail;
}
//creates a string representation of all the values in the list
public String toString()
{
String result = null;
for(int i = 0; i < count; i++)
{
result = i + " : " + get(i).toString();
}
return result;
}
//removes all the values in the list
public void clear()
{
for(int i = count -1; i >= 0; i++)
{
removeAt(i);
}
}
//searches for a value in the list and returns the first index of that
//value when found
public int search(T find)
{
if(head == null)
{
return -10;
}
MyNode<T> p = head;
do
{
if(find.compareTo(p.data) == 0)
{
return 0;
}
else
{
return -1;
}
p = p.next;
}while(p != null);
}
public void itemChosen(int choice, LLMenu[] menu)
{
LLMenu m = menu[choice-1];
switch(m)
{
case ADD:
System.out.println("What value would you like to add?");
T addThis = scan.nextInt();
add(addThis);
break;
case INSERT:
System.out.println("What index would you like to replace?");
T replace = scan.nextInt();
System.out.println("What number would you like to insert?");
int val = scan.nextInt();
insert(val, replace);
break;
case SIZE:
size();
break;
case GET:
System.out.println("What index would you like to look at?");
int thisOne = scan.nextInt();
get(thisOne);
break;
case REMOVE:
remove();
break;
case REMOVEAT:
System.out.println("What index would you like to remove?");
T thisHere = scan.nextInt();
removeAt(thisHere);
break;
case REMOVELAST:
removeLast();
break;
case TOSTRING:
toString();
break;
case CLEAR:
clear();
break;
case SEARCH:
System.out.println("What value would you like to search for?");
T searchForMe = scan.nextInt();
search(searchForMe);
break;
}
}
}
and MyNode:
public class MyNode<T>
{
T data;
MyNode<T> next;
MyNode<T> previous;
}
Where I'm really having problems is at the switch statement in LList where I am scanning in items that are supposed to be set to Generics and obviously there is no method using Scanners to read in Generics. So question1, how do I read in and set these to Generics, and question2, in my clear method in LList how do I send variable i when using removeAt when it is expecting a Generic? Please keep all answers relevant and thanks for your time!
Edit
One more question in my search method inside the do-while there is an if statement that says if(find.compareTo(p.data) == 0) how can I change this so that it works? I wasn't really sure of what to put there so I kind of just wrote my thought down.

#1. You can implement generic console input method on your own - here is an example: Improvement/s to my Java generic console input method?

I believe your itemChosen code should be in the main method.
You clearly need to declare the T type.
public void main(String[] args)
{
LList<Integer> myLList = new LList<>();
}
Now add your desired case-switch code.

Related

How can I Search for a node's contents in a Generic Linked List with a String Input?

I am trying to return all node contents that match a given String input. What I am trying to do is essentially a very simple search engine, where the user is able to type in a String and the program returns all characteristically similar contents it can find in the linked list. The linked list itself is built from a file, formatted as
<<Game’s Name 0>>\t<<Game’s Console 0>>\n
<<Game’s Name 1>>\t<<Game’s Console 1>>\n
where the lines are delimited with a \n and the game and its corresponding console are delimited with a \t.
My current methodology follows searching the linked list with a while loop, assigning a temporary value to the head and reassigning it to it's link as it goes down the list. Once the loop finds contents within a node that matches the current input, it stops the loop and returns the data found in the node. I have yet to try if this could be done with a for loop, as the while loop more than likely would not know when to continue once it has found a match. I am also unsure if the while loop argument is the most efficient one to use, as my understanding of it is very minimal. I believe !temp.equals(query) is stating "temp does not equal query," but I have a feeling that this could be done in a more efficient manner.
This is what I have so far, I will provide the entire Generic linked list class for the sake of context, but the method I am questioning is the very last one, found at line 126.
My explicitly stated question is how can I search through a linked list's contents and return those contents through the console.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class GenLL<T>
{
private class ListNode
{
T data;
ListNode link;
public ListNode(T aData, ListNode aLink)
{
data = aData;
link = aLink;
}
}
private ListNode head;
private ListNode current;
private ListNode previous;
private int size;
public GenLL()
{
head = current = previous = null;
this.size = 0;
}
public void add(T aData)
{
ListNode newNode = new ListNode(aData, null);
if (head == null)
{
head = current = newNode;
this.size = 1;
return;
}
ListNode temp = head;
while (temp.link != null)
{
temp = temp.link;
}
temp.link = newNode;
this.size++;
}
public void print()
{
ListNode temp = head;
while (temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}
public void addAfterCurrent(T aData)
{
if (current == null)
return;
ListNode newNode = new ListNode(aData, current.link);
current.link = newNode;
this.size++;
}
public T getCurrent()
{
if(current == null)
return null;
return current.data;
}
public void setCurrent(T aData)
{
if(aData == null || current == null)
return;
current.data = aData;
}
public void gotoNext()
{
if(current == null)
return;
previous = current;
current = current.link;
}
public void reset()
{
current = head;
previous = null;
}
public boolean hasMore()
{
return current != null;
}
public void removeCurrent()
{
if (current == head)
{
head = head.link;
current = head;
}
else
{
previous.link = current.link;
current = current.link;
}
if (this.size > 0)
size--;
}
public int getSize()
{
return this.size;
}
public T getAt(int index)
{
if(index < 0 || index >= size)
return null;
ListNode temp = head;
for(int i=0;i<index;i++)
temp = temp.link;
return temp.data;
}
public void setAt(int index, T aData)
{
if(index < 0 || index >= size || aData == null)
return;
ListNode temp = head;
for (int i = 0; i < index; i++)
temp = temp.link;
temp.data = aData;
}
public T search() throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Search: ");
String query = keyboard.nextLine();
ListNode temp = head;
while(!temp.equals(query))
temp = temp.link;
return temp.data;
//plus some sort of print function to display the result in the console
}
}
You can apply regex for every node's content, if the data type is string apply it if it is of some other datatype convert it into string if possible, else throw some exceptions.

Deleting a node from the linked list

In this linked list I am trying to delete a node and return the list after deleting the particular node. Here I am not using the Value to delete, I am using the position to delete that particular node. Here in my code the delete function seems to have no effect over the output. What am I doing wrong here?
import java.util.*;
class LinkedList{
Node head;
static class Node{
int data;
Node next;
Node(int d){
this.data = d;
next = null;
}
}
public LinkedList insert(LinkedList l, int data){
Node new_node = new Node(data);
if(l.head == null){
l.head = new_node;
}
else{
Node last = l.head;
while(last.next != null){
last = last.next;
}
last.next = new_node;
}
return l;
}
public LinkedList delete(LinkedList l, int position){
Node current = l.head;
if(position == 0){
current = current.next;
}
int index = 1;
while(index < position - 1){
current = current.next;
index++;
}
current = current.next.next;
Node iterating = l.head;
while(iterating != null){
System.out.print(iterating.data + " ");
iterating = iterating.next;
}
return l;
}
}
public class Main
{
public static void main(String[] args) {
LinkedList l = new LinkedList();
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int position = sc.nextInt();
for(int i=0; i<number; i++){
int num = sc.nextInt();
l.insert(l,num);
}
l.delete(l,position);
}
}
current=current.next doesn't have any effect on the original LinkedList because with that line of code, you just change where the reference (named as current) points to.
Think about this way,
Node a = new Node()
Node b = new Node()
Node c = new Node()
a.next =b
a = c
These lines of code doesn't result in c being connected to b.
Change code to this:
if (position == 0) return l.head.next;
else {
Node head = l.head;
int index = 1;
Node itr = l.head;
while(index < position) {
itr = itr.next;
index++;
}
if(itr.next != null) itr.next = itr.next.next;
return head;
}
public LinkedList delete(LinkedList l, int position) {
Node previous = null;
Node current = l.head;
int index = 0;
while (current != null && index < position){
previous = current;
current = current.next;
index++;
}
if (current != null) {
if (previous == null) {
l.head = current.next;
} else {
previous.next = current.next;
}
}
System.out.print("[");
Node iterating = l.head;
while (iterating != null) {
System.out.print(iterating.data + ", ");
iterating = iterating.next;
}
System.out.println("]");
return l;
}
The problem in java is that to delete a node either the head must be changed to its next, or the previous node's next must be changed to current's next.
Then too current might become null, have reached the list's end, position > list length.

Java Doubly Linked List removeLast()

I have a class assignment that required me to create a class DoubleList that implements a ListADT.
I've gotten to the point where the code ALMOST works correctly. The output for the code should be:
1 3 7 9 13 14 16 17 23 24
3 9 13 16
My output is:
1 3 7 9 13 14 16 17 23 24
3 9 13 16 23
The first removeLast() seems to remove the 24 but for some reason the 23 stays after the second removeLast() is called. Please help!
EDIT: If I call removeLast() another time, it removes the 23.
class DoubleList<T> implements ListADT<T>{
private int _size;
private DoubleNode _head;
private DoubleNode _tail;
public DoubleList() {
_size = 0;
_head = null;
_tail = null;
}
public T removeFirst(){
if(_size == 0){
return null;
}
DoubleNode tmp = _head;
_head = _head._next;
_head._previous = null;
_size--;
return tmp._value;
}
public T removeLast(){
if(_size == 0) {
return null;
}
T temp = _tail._value;
_tail = _tail._previous;
_tail._next = null;
_size--;
return temp;
}
public T remove(T element){
if(_size == 0){
return null;
}
DoubleNode current = _head;
DoubleNode previous = null;
T temp = null;
do{
if(current._value == element){
temp = current._value;
if(previous == null){
_head = _head._next;
_head._previous = null;
}
else{
previous._next = current._next;
}
}
previous = current;
current = current._next;
}while(current != null);
return temp;
}
public T first(){
return _head._value;
}
public T last(){
return _tail._value;
}
public boolean contains(T target){
if(_size == 0){
return false;
}
DoubleNode temp = _head;
do{
if(temp._value == target){
return true;
}
temp = temp._next;
}while(temp != null);
return false;
}
public boolean isEmpty(){
if(_size == 0){
return true;
}
return false;
}
public int size(){
return _size;
}
public void add(T element)
{
int add = 0;
DoubleNode temp = new DoubleNode();
temp._value = element;
DoubleNode point = _head;
DoubleNode placeHolder;
if(_head == null) {
_head = temp;
_tail = temp;
_size++;
return;
}
else if((Integer)element <= (Integer)_head._value){
temp._next = _head;
_head._previous = temp;
_head = temp;
_size++;
return;
}
do {
if(point._next == null){
point._next = temp;
temp._previous = point;
_tail = temp;
_size++;
return;
}
else if((Integer)point._next._value >= (Integer)element && (Integer)point._value < (Integer)element){
placeHolder = point._next;
point._next = temp;
placeHolder._previous = temp;
temp._next = placeHolder;
temp._previous = point;
_size++;
return;
}
point = point._next;
} while (point != null);
_size++;
}
public String toString(){
String returnString = "";
if(_size == 0){
return returnString;
}
DoubleNode temp = _head;
do{
returnString += temp._value + " ";
temp = temp._next;
}while(temp != null);
return returnString;
}
private class DoubleNode {
private DoubleNode _previous;
private DoubleNode _next;
private T _value;
public DoubleNode() {
_previous = null;
_next = null;
_value = null;
}
public DoubleNode(T value){
_previous = null;
_next = null;
_value = value;
}
}
}
/**
* DoubleOrderedList testing area.
*
* #author (your name), Acuna
* #version (version)
*/
class Driver {
public static void main(String [] args) {
DoubleList<Integer> list = new DoubleList<>();
//RA: These are _extremely_ simple tests - do not use them when doing
// your writeup.
list.add(23);
list.add(24);
list.add(16);
list.add(3);
list.add(7);
list.add(17);
list.add(9);
list.add(13);
list.add(14);
list.add(1);
System.out.println("\nsize = " + list.size());
System.out.println(list);
list.remove(7);
System.out.println(list);
list.removeFirst();
System.out.println(list);
list.remove(17);
System.out.println(list);
list.removeLast();
System.out.println(list);
list.remove(14);
System.out.println(list);
list.removeLast();
System.out.println(list);
I don't think your bug is in removeLast. It's in the remove function, and it corrupts your list, causing further manipulations of the list to behave incorrectly.
When you remove an item from the middle of a double linked list, you need to stitch up the item before the removed item, and the item after the removed item. You are doing the first operation, but not the second. For example, suppose I have three elements in the list: L X R. I want to remove X. I have to set L._next = R (you do that), and also set R._previous = L (you don't do that). At that point, your list becomes corrupt, because your reverse links are off.
Take a look at your loop at remove function.
do{
if(current._value == element){
temp = current._value;
if(previous == null){
_head = _head._next;
_head._previous = null;
}
else{
previous._next = current._next;
//next line is missing
previous._next._previous = previous;
}
}
previous = current;
current = current._next;
}while(current != null);
Also, it's not efficient to loop while(current != null), consider (while !found && current != null) or break statement.

Reverse generic LinkedList by using swap method

public class SimpleLinkedList<E> {
public Node<E> head;
public int size;
public void add(E e) {
++this.size;
if (null == head) {
this.head = new Node();
head.val = e;
} else {
Node<E> newNode = new Node();
newNode.val = e;
newNode.next = head;
this.head = newNode;
}
}
public void swap(E val1, E val2) {
if (val1.equals(val2)) {
return;
}
Node prevX = null, curr1 = head;
while (curr1 != null && !curr1.val.equals(val1)) {
prevX = curr1;
curr1 = curr1.next;
}
Node prevY = null, curr2 = head;
while (curr2 != null && !curr2.val.equals(val2)) {
prevY = curr2;
curr2 = curr2.next;
}
if (curr1 == null || curr2 == null) {
return;
}
if (prevX == null) {
head = curr2;
} else {
prevX.next = curr2;
}
if (prevY == null) {
head = curr1;
} else {
prevY.next = curr1;
}
Node temp = curr1.next;
curr1.next = curr2.next;
curr2.next = temp;
}
public void reverse() {
Node<E> prev = null;
Node<E> current = head;
Node<E> next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
public static class Node<E> {
public Node<E> next;
public E val;
}
}
public class SimpleLinkedListTest {
#Test
public void testReverseMethod() {
SimpleLinkedList<Integer> myList = new SimpleLinkedList<>();
for (int i = 0; i < 10; i++) {
myList.add(i);
}
SimpleLinkedList<Integer> expectedList = new SimpleLinkedList<>();
for (int i = 9; i > -1; i--) {
expectedList.add(i);
}
myList.reverse();
assertTrue(AssertCustom.assertSLLEquals(expectedList, myList));
}
}
What would be the most optimal way to reverse generic LinkedList by using the swap method?
before reverse method :
(head=[9])->[8]->[7]->[6]->[5]->[4]->[3]->[2]->[1]->[0]-> null
after reverse() method :
(head=[0])->[1]->[2]->[3]->[4]->[5]->[6]->[7]->[8]->[9]-> null
What you need to do is divide the list in half. If the list size is odd the one in the middle will remain in place. Then swap elements on either side in a mirror like fashion. This should be more efficient than O(n^2)
reverse(){
Node current = this.head;
int half = this.size/2;
int midElement = this.size % 2 == 0 ? 0: half + 1;
Stack<Node<E>> stack = new Stack<Node<E>>();
for(int i = 0; i < this.size; i++){
if (i < = half)
stack.push(current);
else{
if (i == midElement)
continue;
else
swap(stack.pop(), current);
current = current.next;
}
}
swap(Node<E> v, Node<E> v1){
E tmp = v.value;
v.value = v1.value;
v1.value = tmp;
}
This is a little bit of pseudo java. It is missing still the checks for size = 0 or size = 1 when it should return immediately. One for loop. Time Complexity O(n). There is also the need to check when size = 2, swap(...) is to be invoked directly.
Based on the #efekctive 's idea, there a solution. The complexity is a little bit worse than O^2 but no need changes in the swap method, no need in usage of another collection. The code below passes the unit test, however, be careful to use it there could be a bug related to size/2 operation. Hope this help.
public void reverse() {
Node<E> current = head;
SimpleLinkedList<E> firstHalf = new SimpleLinkedList<>();
SimpleLinkedList<E> secondHalf = new SimpleLinkedList<>();
for (int i = 0; i < size; i++) {
if (i >= size / 2) {
firstHalf.add(current.val);
} else {
secondHalf.add(current.val);
}
current = current.next;
}
SimpleLinkedList<E> secondHalfReverse = new SimpleLinkedList<>();
for (int i = 0; i < secondHalf.size(); i++) {
secondHalfReverse.add(secondHalf.get(i));
}
for (int i = 0; i < size / 2; i++) {
if (secondHalfReverse.get(i) == firstHalf.get(i)) {
break;
}
swap(secondHalfReverse.get(i), firstHalf.get(i));
}
}

Sorting a Linked List Alphabetically without using Java Library

I am trying to sort my singly linked list by the method I wrote below. I tried to use bubble sort but I don't think mine is sorting properly. By the way I am not getting any NullPointerException.
public void lister()
{
int n, c, d, swap;
Node tempNode = head;
for (c = 0; c < ( size - 1 ); c++)
{
tempNode = head;
for (d = 0; d < size - c - 1; d++)
{
String compare1 = ((Person)tempNode.getNext().getElement()).getName() + " " +
((Person)tempNode.getNext().getElement()).getSur();
String compare2 = ((Person)tempNode.getElement()).getName() + " " +
((Person)tempNode.getElement()).getSur();
if (compare1.compareTo(compare2) < 0)
{
Person tempPerson = (Person) tempNode.getElement();
tempNode.setElement(tempNode.getNext().getElement());
tempNode.getNext().setElement(tempPerson);
}
if(tempNode.getNext() != null)
tempNode = tempNode.getNext();
} // End of inner for loop
} // End of outer for loop
} // End of lister function
Where my inputs for Person objects' name and surname fields are:
name: aaaa , surname: aaaa
name: cccc , surname: cccc
name: bbbb , surname: bbbb
I am getting this as the sorted output:
aaaa aaaa
bbbb bbbb
bbbb bbbb
The other source codes I used that you may want to check:
list() method:
private static void list()
{
contactList.lister();
contactList.listResults();
int listNum = input.nextInt();
contactList.getInOrder(listNum);
}
SLinkedList class:
import java.util.*;
/** Singly linked list implementation .*/
public class SLinkedList<E> implements LinkedList<E>, Iterable<E>
{
protected Node<E> head; // head node of the list
protected Node<E> tail; // tail node of the list
protected int size; // number of nodes in the list
public Iterator<E> iterator()
{
return new LinkedListIterator(head);
}
/** Default constructor that creates an empty list */
public SLinkedList()
{
head = null;
tail = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst(E newElement)
{
Node<E> newNode = new Node(newElement,null);
if(size == 0) //if list is empty
tail = newNode;
newNode.setNext(head);
head = newNode;
size++;
}
public void addLast(E newElement)
{
Node<E> newNode = new Node(newElement,null);
if(size == 0) //if list is empty
head = newNode;
if (size != 0) //if list is not empty
tail.setNext(newNode);
tail = newNode;
size++;
}
public E removeFirst()
{
Node<E> tempNode = null;
if (size != 0) {
if(size == 1)
tail = null;
tempNode = head;
head = head.getNext();
tempNode.setNext(null);
size--;
//if list is empty then return null
return tempNode.getElement();
}
public E removeLast()
{
Node<E> tempNode = head;
if(size == 0)
return null;
if(size == 1) {
head = null;
tail = null;
size--;
return tempNode.getElement();
}
//size is greater than 1
for(int i=1; i<=size-2; i++) {
tempNode = tempNode.getNext(); //go to element that before the tail
}
Node<E> tempNode2 = tail;
tail = tempNode;
tail.setNext(null);
size--;
return tempNode2.getElement();
}
public void remove(E element)
{
int index = 0;
boolean found = false;
Node<E> temp = head;
for(int i=1; i<=size; i++) { //find the node with element
index++;
if(temp.getElement().equals(element)){
found = true;
break;
}
temp = temp.getNext();
}
if(found){
if(index == 1)
removeFirst();
else if(index == size)
removeLast();
}
else{
//find the previous node
Node<E> prev = head;
for(int i=1; i<index-1; i++) {
prev = prev.getNext();
}
prev.setNext(temp.getNext());
temp.setNext(null);
size--;
}
}
public int searchList(E searchKey) {
if(size == 0)
return -1;
Node tempNode = head;
for(int i=1; i<=size; i++) {
if(tempNode.getElement().equals(searchKey))
return i; //return index of the node
tempNode = tempNode.getNext();
}
return -1; //not found
}
public void printList() {
Node tempNode = head;
for(int i=1; i<=size; i++) {
System.out.print(tempNode.getElement());
if(i!=size) //if it is not last element
System.out.print(" - ");
tempNode = tempNode.getNext();
}
System.out.println();
}
public void listResults()
{
Node tempNode = head;
for(int i = 1; i <= size; i++)
{
System.out.println(i + ". " +((Person) tempNode.getElement()).getName() + " " +
((Person) tempNode.getElement()).getSur());
tempNode = head.getNext();
}
}
public void getInOrder(int o)
{
Scanner input = new Scanner(System.in);
Node tempNode = head;
for(int i=1; i <= size; i++)
{
if(i==o)
{
System.out.println(tempNode.getElement());
}
tempNode = tempNode.getNext();
}
System.out.println("a:[<=] d:[=>] u:[update] i:[insert] r:[delete] e:[exit]");
String action = input.next();
if(action.equals("e"))
{
}
else if(action.equals("a") && (o-1) != 0)
{
getInOrder(o - 1);
}
else if(action.equals("d") && (o+1) <= 9)
{
getInOrder(o + 1);
}
else if(action.equals("u"))
{
System.out.println("New Name: ");
String nName = input.next();
System.out.println("New Surname: ");
String nSur = input.next();
System.out.println("New Address: ");
String nAdd = input.next();
((Person)tempNode.getElement()).setName(nName);
((Person)tempNode.getElement()).setSur(nSur);
((Person)tempNode.getElement()).setAdd(nAdd);
}
else if(action.equals("i"))
{
System.out.println("Add a new number:\nType the type of the phone number:");
String phoneType = input.next();
System.out.println("Type the number: ");
int phoneInput = input.nextInt();
((Person) getFromResults(o)).insertPhone(new PhoneNumber(phoneInput,phoneType));
}
else if(action.equals("r"))
{
//NullPointerException
int index = 0;
boolean found = false;
Node<E> temp = head;
for(int i=1; i<=size; i++) {//find the node with element
index++;
if(tempNode.getElement().equals(temp.getElement())){
found = true;
break;
}
temp = temp.getNext();
}
if(found){
if(index == 1)
removeFirst();
else if(index == size)
removeLast();
else{
//find the previous node
Node<E> prev = head;
for(int i=1; i<index-1; i++) {
prev = prev.getNext();
}
prev.setNext(temp.getNext());
temp.setNext(null);
size--;
}
}
}
}
public void lister()
{
//Alternative bubble sort i found from internet.
int n, c, d, swap;
Node tempNode = head;
for (c = 0; c < ( size - 1 ); c++)
{
tempNode = head;
for (d = 0; d < size - c - 1; d++)
{
String compare1 = ((Person)tempNode.getNext().getElement()).getName() + " " +
((Person)tempNode.getNext().getElement()).getSur();
String compare2 = ((Person)tempNode.getElement()).getName() + " " +
((Person)tempNode.getElement()).getSur();
if (compare1.compareTo(compare2) < 0)
{
Person tempPerson = (Person) tempNode.getElement();
tempNode.setElement(tempNode.getNext().getElement());
tempNode.getNext().setElement(tempPerson);
}
if(tempNode.getNext() != null)
tempNode = tempNode.getNext();
}
}
}
}

Categories

Resources