I am new to java, so sorry in advance if this is horrible. Basically, I believe that you need to insert a number, say, a linked list [10 30 50 70] I want to insert 40, so I type in the next, and then again, and now I'm at 50. I want to insert earlier, but when I I type up to, and then 40 it just returns [10 30 50 70] total = 4, and the current is 50.
public void insertAfter(long dd) {
Node newNode = new Node(dd);
newNode = current;
current = previous;
if (current != null) {
return;
}
else {
newNode = current;
}
}
public void insertBefore(long dd) {
Node newNode = new Node(dd);
current = previous;
newNode = current;
}
Here is the code that calls these two methods and provides a list. Any suggestions?
package hw4;
import java.io.*;
class TestLinkList {
public static void main(String[] args) throws IOException
{
LinkList theList = new LinkList();
theList.insertFirst(70);
theList.insertFirst(50);
theList.insertFirst(30);
theList.insertFirst(10);
theList.reset();
while(true) {
System.out.print("Enter first letter of reset, ");
System.out.print("next, get, before, after, delete, exit: ");
System.out.flush();
int choice = getChar();
long value;
switch(choice)
{
case 'r':
theList.reset();
theList.displayList();
break;
case 'e':
break;
case 'n':
if( theList.getCurrent() != null ) {
theList.nextLink();
theList.displayList();
} else
System.out.println("Can't go to next link");
break;
case 'g':
if( theList.getCurrent() != null ) {
value = theList.getCurrent().dData;
System.out.println("Returned " + value);
}
else
System.out.println("List is empty");
break;
case 'b':
System.out.print("Enter value to insert: ");
System.out.flush();
value = getInt();
theList.insertBefore(value);
theList.displayList();
break;
case 'a':
System.out.print("Enter value to insert: ");
System.out.flush();
value = getInt();
theList.insertAfter(value);
theList.displayList();
break;
case 'd':
if( theList.getCurrent() != null ) {
value = theList.deleteCurrent();
System.out.println("Deleted " + value);
theList.displayList();
} else
System.out.println("Can't delete");
break;
default:
System.out.println("Invalid entry");
}
if (choice == 'e') break;
}
}
public static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
public static char getChar() throws IOException {
String s = getString();
return s.charAt(0);
}
public static int getInt() throws IOException {
String s = getString();
return Integer.parseInt(s);
}
}
source
share