multiple link list sort in java alphabetically - java

I wanted some help with the multiple indexed linked list. I am trying to sort a set of names alphabetically and i don't even know how to start at all. I tried some of the code while searching in google but the case is i know how the code works but i don't where to put that code. so if you could help me i would really appreciate it. Thanks in advance....
This is my node class ....
public class node {
String data;long id;
node next;
public node(String data){
this.data = data;
this.id = getId(data);
}
public long getId(String line)
{
int i;
long id=0;
String s= null;
char a;
int j=2;
for(i = 0;i <3;i++)
{
a = line.charAt(i);
id += Character.getNumericValue(a) * Math.pow(26, j);
j--;
}
return id;
}
public long getId()
{
return id;
}
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;
}
}
This is my linked list class........
public class LinkedList {
private node front;
public void init(){
front = null;
}
public node makeNode(String data){
node newNode = new node(data);
return newNode;
}
public node findTail(node head){
node current = front;
while(current.next != null){
current = current.next;
}
return current;
}
public node findSpot(String num) {
node current = front;
boolean searching = true, found = false;
while((searching)&&(!found)) {
if(current == null) {
searching = false;
}
else if(current.data == num) {
found = true;
}
else {
current = current.next;
}
}
return current;
}
public void deleteAfter(node spot)
{
node nextNode;
nextNode = spot.next;
spot.next = nextNode.next;
}
public void addNodeAtEndOfList(String data){
if(front == null){
front = makeNode(data);
}else{
node tail;
tail = findTail(front);
tail.next = makeNode(data);
}
}
public void addAfter(node spot, String data)
{
node newNode;
newNode = makeNode(data);
newNode.next = spot.next;
spot.next = newNode;
}
public void addBefore(node spot, String data)
{
node newNode;
if(front == null || spot.data == front.data){
front = makeNode(data);
front.next= spot;
}
else{
newNode = makeNode(data);
node tail = front;
if(tail.next == spot)
{
tail.next = newNode;
newNode.next = spot;
}
else{
while((tail.next).next!= spot)
tail= tail.next;
tail.next = newNode;
newNode.next = spot;
}
}
}
public void makeIndexList()
{
node spot;
int currAlpha;
indexNode AlphaIndex[26];
/* Fill in the index array. */
for (int j=0 ;j<26; j++) {
currAlpha = j;
AlphaIndex[j].weight = currAlpha;
spot = findSpot(currAlpha);
if (spot is equal to the front of the list) and
(spot.weight > (currWeight + 10)) {
weightIndex[j].firstOne = null;
}
else {
weightIndex[j].firstOne = spot;
}
}
}
public void showList(){
node current = front;
int i = 0;
while(current != null){
System.out.println("a["+i+"] = " + current.data);
current = current.next;
i++;
}
}
}
public class indexNode {
int alpha;
node firstOne;
}
this is my filein class..
import java.util.Scanner;
import java.io.*;
public class fileIn {
String fname;
LinkedList mylist = new LinkedList();
node front;
public fileIn() {
//System.out.println("Constructor");
getFileName();
readFileContents();
System.out.print(mylist.showList());
}
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
//System.out.println("line = "+ line);
mylist.addNodeAtEndOfList(line);
j = 0;
len = line.length();
/*for(j=0;j<len;j++){
//System.out.println("line["+j+"] = "+line.charAt(j));
}*/
}
} /* End while. */
mylist.showList();
} /* End try. */
catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}
}

The get-the-job-done way to do this looks like this.
package org.jproggy;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Sorter {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(args[0])));
String line;
List<String> lines = new LinkedList<>();
while ((line = in.readLine()) != null) {
lines.add(line);
}
in.close();
Collections.sort(lines, String.CASE_INSENSITIVE_ORDER);
for (String val: lines) {
System.out.println(val);
}
}
}
After compiling the class you can call it with
java org.jproggy.Sorter <path-to-file>
If you prefer to learn about building data structures or sorting algorithms you need to be more specific in what you want. But the sources of the JDK are available and there you can learn much how things are done well.
Btw. in java 8 it might even look like this:
Path path = FileSystems.getDefault().getPath(args[0]);
BufferedReader data = Files.newBufferedReader(path);
data.lines().sorted(String.CASE_INSENSITIVE_ORDER).forEach(System.out::println);
Nice.

Related

Iterating a linked list

I am having a little trouble iterating a linked list for an assignment.
Linked list class / Node class
(no size methods & cannot modify/add methods)
class MyGenericLinkedList<S> {
Node<S> front;
public MyGenericLinkedList() {
front = null;
}
public void add(S value) {
if (front == null) {
front = new Node<S>(value);
} else {
Node<S> current = front;
while (current.next != null) {
current = current.next;
}
current.next = new Node<S>(value);
}
}
public S get(int index) {
Node<S> current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return (S)current.data;
}
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
Node<S> current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS Node ***/
class Node<X> {
X data;
Node<X> next;
public Node(X data) {
this.data = data;
this.next = null;
}
public Node(X data, Node<X> next) {
this.data = data;
this.next = next;
}
}
Here is what I am trying to use to iterate the list but is not running
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.remove(0);
}
My full java file:
/*** DO NOT ADD A NEW IMPORT DECLARATION HERE ***/
/*** DO NOT MAKE ANY CHANGE TO CLASS A5 EXCEPT THE PLACEHOLDER TO FILL IN ***/
/*** YOU CANNOT ADD A NEW FIELD VARIABLE ***/
/*** YOU CANNOT ADD A NEW METHOD DECLARATION ***/
public class A5 {
public static void main(String[] args) {
//---------------------------------------------------------------------
TreeNode root = new TreeNode(1);
MyGenericLinkedList<TreeNode> children = new MyGenericLinkedList();
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
TreeNode six = new TreeNode(6);
TreeNode seven = new TreeNode(7);
TreeNode eight = new TreeNode(8);
TreeNode nine = new TreeNode(9);
TreeNode ten = new TreeNode(10);
TreeNode eleven = new TreeNode(11);
TreeNode twelve = new TreeNode(12);
TreeNode thirteen = new TreeNode(13);
TreeNode fourteen = new TreeNode(14);
children.add(two);
children.add(three);
children.add(four);
root.setChildren(children);
children.remove(0);
children.remove(0);
children.remove(0);
children.add(five);
children.add(six);
two.setChildren(children);
children.remove(0);
children.remove(0);
children.add(ten);
children.add(eleven);
four.setChildren(children);
children.remove(0);
children.remove(0);
children.add(seven);
children.add(eight);
children.add(nine);
six.setChildren(children);
children.remove(0);
children.remove(0);
children.remove(0);
children.add(twelve);
ten.setChildren(children);
children.remove(0);
children.add(thirteen);
children.add(fourteen);
twelve.setChildren(children);
children.remove(0);
children.remove(0);
//---------------------------------------------------------------------
/*** DO NOT MAKE ANY CHANGE TO THE FOLLOWING CODE ***/
MyGenericTree<Integer> tree = new MyGenericTree<Integer>(root);
tree.traverseInPostOrder();
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS MyGenericTree EXCEPT THE PLACEHOLDER TO FILL IN ***/
/*** YOU CANNOT ADD A NEW FIELD VARIABLE ***/
/*** YOU CANNOT ADD A NEW METHOD DECLARATION ***/
class MyGenericTree<T> {
private TreeNode<T> root = null;
public MyGenericTree(TreeNode<T> root) {
this.root = root;
}
public void traverseInPostOrder() {
traverseInPostOrder(root);
}
public void traverseInPostOrder(TreeNode<T> node) {
//---------------------------------------------------------------------
System.out.println("1");
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.remove(0);
}
/*
if(node.children == null){
System.out.print(node.data);
}
else{
TreeNode curr = node.children.get(0);
int i = 1;
while(curr != null) {
MyGenericTree<Integer> currNode = new MyGenericTree<Integer>(curr);
//curr = node.children.get(i);
currNode.traverseInPostOrder();
//curr = curr.next;\
i++;
}
System.out.print(node.data);
}
*/
//---------------------------------------------------------------------
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS TreeNode ***/
class TreeNode<N> {
N data = null;
TreeNode<N> parent = null;
MyGenericLinkedList<TreeNode<N>> children = null;
public TreeNode(N data) {
this.data = data;
}
public void setChildren(MyGenericLinkedList<TreeNode<N>> children) {
this.children = children;
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS MyGenericLinkedList ***/
class MyGenericLinkedList<S> {
Node<S> front;
public MyGenericLinkedList() {
front = null;
}
public void add(S value) {
if (front == null) {
front = new Node<S>(value);
} else {
Node<S> current = front;
while (current.next != null) {
current = current.next;
}
current.next = new Node<S>(value);
}
}
public S get(int index) {
Node<S> current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return (S)current.data;
}
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
Node<S> current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS Node ***/
class Node<X> {
X data;
Node<X> next;
public Node(X data) {
this.data = data;
this.next = null;
}
public Node(X data, Node<X> next) {
this.data = data;
this.next = next;
}
}
Based on how you have the iterator, that can potentially destroy the linked list after having it print out. Generally, when working with linked lists, you want to keep the list. Below is the basic concept of iterating through a linked list.
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.front = node.children.front.next
}
At any point, you only have access to single node, so if you want to go to the next node, you will have to set the current node to the next in the list. Since it might be null, that is why you'd have a conditional checking if the node is set to a null value. If it is set to a null value, you are at the end of the linked list.

Can't access my linked list methods and can't iterate trough it

So im following along this playlist about data structures and in this video to conclude the linked list part, the professor explain we need an inner class called IteratorHelper.
Video:
https://www.youtube.com/watch?v=bx0ebSGUKto&list=PLpPXw4zFa0uKKhaSz87IowJnOTzh9tiBk&index=21
This is the code in my github with the linked list implementation and the main class called tester:
https://github.com/Ghevi/Algos-DataStructures/tree/master/src/com/ghevi/ads/linkedlists
The problem is that the tester class can't compile. If I instantiate the linked list as an ListIterator i can't access its methods. I also can't iterate trough it regardless of having the IteratorHelper inner class.
In the video he writes "implements ListI<>" is just a shorter version for ListIterator<>?
Sorry im just a beginner.
package com.ghevi.ads.linkedlists;
import java.util.ListIterator;
public class Tester {
public static void main(String[] args) {
ListIterator<Integer> list = new LinkedList<Integer>();
int n = 10;
for (int i = 0; i < n; i++)
list.addFirstWithTail(i);
int removedFirst = list.removeFirst();
int removedLast = list.removeLast();
for(int x : list){
System.out.println(x);
}
}
}
The video is not very clear, but basically LinkedList should implement Iterable, not ListIterator. IteratorHelper should implement ListIterator (see 4:20 timestamp).
Here's the fixed code:
package linkedlists;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
// Notes at Notes/Singly LinkedList.txt
public class LinkedList<E> implements Iterable<E> {
#Override
public Iterator<E> iterator() {
return new IteratorHelper();
}
class IteratorHelper implements ListIterator<E>{
Node<E> index;
public IteratorHelper(){
index = head;
}
// Return true if there is an element to return at the pointer
#Override
public boolean hasNext() {
return (index != null);
}
// Return the element where the pointer is and mover the pointer to the next element
#Override
public E next() {
if(!hasNext())
throw new NoSuchElementException();
E val = index.data;
index = index.next;
return val;
}
#Override
public boolean hasPrevious() {
return false;
}
#Override
public E previous() {
return null;
}
#Override
public int nextIndex() {
return 0;
}
#Override
public int previousIndex() {
return 0;
}
#Override
public void remove() {
}
#Override
public void set(E e) {
}
#Override
public void add(E e) {
}
/* For version older than java 1.8
public void remove(){
throw new UnsupportedOperationException();
}
public void forEachRemaining(){};
*/
} // inner class (can only be accessed by the outer class)
class Node<E> {
E data;
Node<E> next;
public Node(E obj){
data = obj;
next = null;
}
} // inner class (can only be accessed by the outer class)
private Node<E> head;
private Node<E> tail;
private int currentSize;
public LinkedList(){
head = null;
tail = null;
currentSize = 0;
}
public void addFirst(E obj){
Node<E> node = new Node<E>(obj);
// The order of these 2 lines is fundamental
node.next = head;
head = node;
currentSize++;
}
public void addFirstWithTail(E obj){
Node<E> node = new Node<E>(obj);
if(head == null){
head = tail = node;
return;
}
// The order of these 2 lines is fundamental
node.next = head;
head = node;
currentSize++;
}
// O(n)
public void slowAddLast(E obj){
Node<E> node = new Node<E>(obj);
if(head == null){
head = tail = node;
currentSize++;
return;
}
Node<E> tmp = head;
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = node;
currentSize++;
}
// O(1)
public void fasterAddLast(E obj){
Node<E> node = new Node<E>(obj);
if(head == null){
head = tail = node;
currentSize++;
return;
}
tail.next = node;
tail = node;
currentSize++;
}
public E removeFirst(){
if(head == null){
return null;
}
E tmp = head.data;
if(head == tail){
head = tail = null;
} else {
head = head.next;
}
currentSize--;
return tmp;
}
public E removeLast(){
if(head == null){
return null;
}
if(head == tail){
return removeFirst();
}
Node<E> current = head; // Can also write Node<E> current = head, previous = null;
Node<E> previous = null;
while(current != tail){
// The order is crucial
previous = current;
current = current.next;
}
previous.next = null;
tail = previous;
currentSize--;
return current.data;
}
public E findAndRemove(E obj){
Node<E> current = head, previous = null;
// In an empty list current = null so we skip to the last line
while(current != null){
if(((Comparable<E>)obj).compareTo(current.data) == 0){
// Beginning or single element
if(current == head)
return removeFirst();
// Ending of the list
if(current == tail)
return removeLast();
currentSize--;
// Removing the reference to the node to delete
previous.next = current.next;
return current.data;
}
previous = current;
current = current.next;
}
// Node not found
return null;
}
public boolean contains(E obj){
Node<E> current = head;
while(current != null) {
if(((Comparable<E>) obj).compareTo(current.data) == 0)
return true;
current = current.next;
}
return false;
}
public E peekFirst(){
if(head == null)
return null;
return head.data;
}
public E peekLast(){
if(tail == null)
return null;
return tail.data;
}
}
The interface methods hasPrevious, next, etc... have been moved into the IteratorHelper class which implements Iterator. The LinkedList class has an iterator() method because it implements Iterable. Now you can instantiate a LinkedList object and iterate over it in a for-loop:
package linkedlists;
public class Tester {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
int n = 10;
for (int i = 0; i < n; i++)
list.addFirstWithTail(i);
int removedFirst = list.removeFirst();
int removedLast = list.removeLast();
for(int x : list){
System.out.println(x);
}
}
}
Here's a handy chart to remind you which class should have which functions:
More on Iterable vs Iterator

implementing circular linked list with java generics

I am learning java and i am still a beginner.i have written this code to implement a circular linked list and it keeps printing the numbers when i try to print the list. it looks like some kind of an infinite loop maybe. I even tried to use a debug but it didn't do much for me. I would very much appreciate it if you could review the code and see why this is happening. here is the code below. I would be also for giving me feedback on the code :)
this is the class for the circular linked list
public class CircularLinkedList<E> implements API<E> {
private Node<E> head;
private int size = 0;
public void placeAtBeginning(E element) {
Node<E> newNode = new Node<E>(element);
if(head == null) {
head = newNode;
head.setNext(head);
}else {
Node<E> temp = head;
head = newNode;
newNode.setNext(temp);
}
size++;
}
public void placeAtEnd(E element) {
Node<E> newNode = new Node<E>(element);
if (head == null) {
head = newNode;
}else {
Node<E> temp = head;
while (temp.getNext() != head) {
temp = temp.getNext();
}
temp.setNext(newNode);
}
newNode.setNext(head);
size++;
}
public void deleteFromBeginning() {
Node<E> temp = head;
while (temp.getNext() != head) {
temp = temp.getNext();
}
temp.setNext(head.getNext());
head = head.getNext();
size --;
}
public void deleteFromEnd() {
Node<E> temp = head;
while(temp.getNext().getNext() != head) {
temp = temp.getNext();
}
temp.setNext(head);
size--;
}
public void print() {
Node<E> temp = head;
while(temp.getNext()!= head) {
System.out.print(temp.getValue() + " , ");
temp = temp.getNext();
}
System.out.print(temp.getValue());
}
}
this is the class for my node
public class Node<T> {
private Node<T> next;
private T item;
public Node(T item) {
this.item = item;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> getNext() {
return this.next;
}
public T getValue() {
return this.item;
}
}
this is my main where i tried to test it using int.
public class Main {
public static void main(String [] args) {
API <Integer> list = new CircularLinkedList<Integer>();
int a = 10;
int b = 3;
int c = 15;
int d = 8;
int f = 9;
list.placeAtBeginning(a);
list.placeAtEnd(b);
list.print();
System.out.println();
list.placeAtBeginning(c);
list.placeAtBeginning(d);
list.print();
}
}
this is my API which I used
public interface API <E> {
public void placeAtBeginning(E element);
public void placeAtEnd(E element);
public void deleteFromBeginning();
public void deleteFromEnd();
public void print();
}
Your method placeAtBeginning() doesn't insert the new element in the circular list but simply lets the next of the new element refer to the original circular list.
Try this:
public void placeAtBeginning(E element)
{
Node<E> newNode = new Node<E>(element);
if(head == null)
{
head = newNode;
head.setNext(head);
}
else
{
Node<E> last = head;
while (last.getNext() != head)
last = last.getNext();
newNode.setNext(head);
head = newNode;
last.setNext(head);
}
size++;
}
I didn't check the other methods. They might contain a similar error.

Remove Method for a Single and Double Linked List (Java)

I am struggling to understand how to implement a remove(); for both a double and single linked class. I have figured out how to remove the first node in the double, but not in the single. First I would like to debug, problem solve the single linked class, then work on the double after that.
Here is the code I have so far for the Single Linked Class.
public class SingleLinkedClass<T> {
private Node <T> head;
private Node <T> tail;
private int size;
public SingleLinkedClass() {
size = 0;
head = null;
tail = null;
}
public void insertAtHead(T v)
{
//Allocate new node
Node newNode = new Node(v, head);
//Change head to point to new node
head = newNode;
if(tail == null)
{
tail = head;
}
//Increase size
size++;
}
public void insertAtTail(T v)
{
if(tail == null)
{
tail = new Node(v, null);
head = tail;
size++;
return;
}
Node newNode = new Node(v, null);
tail.nextNode = newNode;
tail = newNode;
size++;
}
public T removeHead()
{
if(head == null)
{
throw new IllegalStateException("list is empty! cannot delete");
}
T value = head.value;
head = head.nextNode;
size--;
return value;
}
public void removeTail()
{
//Case 1: list empty
if(head == null)
{
return;
}
//Case 2: list has one node
else if(head == tail)
{
head = tail = null;
}
else
{
Node temp = head;
while(temp.nextNode != tail)
{
temp = temp.nextNode;
}
tail = temp;
tail.nextNode = null;
}
size--;
}
public boolean remove(T v) {
Node<T> previous = head;
Node<T> cursor = head.nextNode;
if (head.nextNode == null) {
return false;
}
while(cursor != tail){
if (cursor.value.equals(v)) {
previous = cursor.nextNode;
return true;
}
previous = cursor;
cursor = cursor.nextNode;
}
return false;
}
public String toString() {
if (head == null) {
return "The list is Empty!";
}
String result = "";
Node temp = head;
while (temp != null) {
result += temp.toString() + " ";
temp = temp.nextNode;
}
return result;
}
public int size() {
return size;
}
private class Node <T> {
private T value;
private Node <T> nextNode;
public Node(T v, Node<T> n) {
value = v;
nextNode = n;
}
public String toString() {
return "" + value;
}
}
}
Here is my Double Linked Class
public class DoubelyLinkedList<E> {
private int size;
private Node<E> header;
private Node<E> trailer;
public DoubelyLinkedList() {
size = 0;
header = new Node<E>(null, null, null);
trailer = new Node<E>(null, null, header);
header.next = trailer;
}
public boolean remove(E v) {
//If the list is empty return false
if(header.next == trailer){
return false;
}
//If v is the head of the list remove and return true
Node <E> cursor = header.next;
for (int i = 0; i < size; i++) {
//Remove at Head
if(cursor.value.equals(v)){
removeAtHead();
}
cursor = cursor.next;
}
return true;
}
/*
} */
public void insertAtHead(E v) {
insertBetween(v, header, header.next);
}
public void insertAtTail(E v) {
insertBetween(v, trailer.prev, trailer);
}
private void insertBetween(E v, Node<E> first, Node<E> second) {
Node<E> newNode = new Node<>(v, second, first);
first.next = newNode;
second.prev = newNode;
size++;
}
public E removeAtHead() {
return removeBetween(header, header.next.next);
}
public E removeAtTail() {
return removeBetween(trailer.prev.prev, trailer);
}
private E removeBetween(Node<E> first, Node<E> second) {
if (header.next == trailer)// if the list is empty
{
throw new IllegalStateException("The list is empty!");
}
E result = first.next.value;
first.next = second;
second.prev = first;
size--;
return result;
}
public String toStringBackward() {
if (size == 0) {
return "The list is empty!";
}
String r = "";
Node<E> temp = trailer.prev;
while (temp != header) {
r += temp.toString() + " ";
temp = temp.prev;
}
return r;
}
public String toString() {
if (size == 0) {
return "The list is empty!";
}
String r = "";
Node<E> temp = header.next;
while (temp != trailer) {
r += temp + " ";
temp = temp.next;
}
return r;
}
private static class Node<T> {
private T value;
private Node<T> next;
private Node<T> prev;
public Node(T v, Node<T> n, Node<T> p) {
value = v;
next = n;
prev = p;
}
public String toString() {
return value.toString();
}
}
}
Here is my Driver
public class Driver {
public static void main(String[] args) {
DoubelyLinkedList<String> doubley = new DoubelyLinkedList();
SingleLinkedClass<String> single = new SingleLinkedClass();
single.insertAtHead("Bob");
single.insertAtHead("Sam");
single.insertAtHead("Terry");
single.insertAtHead("Don");
System.out.println(single);
single.remove("Bob");
System.out.println("Single Remove Head: " + single);
/*
single.remove("Don");
System.out.println("Single Remove Tail: " + single);
single.remove("Terry");
System.out.println("Single Remove Inbetween: " + single);
*/
System.out.println();
System.out.println();
doubley.insertAtHead("Bob");
doubley.insertAtHead("Sam");
doubley.insertAtHead("Terry");
doubley.insertAtHead("Don");
System.out.println(doubley);
doubley.remove("Bob");
System.out.println("Double Remove Head: " + doubley);
doubley.remove("Don");
System.out.println("Double Remove Tail: " + doubley);
/*
doubley.remove("Sam");
System.out.println("Double Remove Inbetween: " + doubley);
*/
}
}
In the removeHead moving head to its next, it might become null. Then tail was the head too. Then tail should be set to null too.
DoublyLinkedList is better English than DoubelyLinkedList.
As this is homework, I leave it by this.

Removing Item at index from a linked list?

public class LinkedList
{
private Node head;
private Node tail;
private int numberOfElements;
public LinkedList()
{
head = null;
tail = null;
this.numberOfElements = 0;
}
public int length()
{
return this.numberOfElements;
}
public void removeFront()
{
Node currNode = head;
head = head.getNextNode();
currNode.setNextNode(null);
this.numberOfElements--;
}
public void removeLast()
{
this.tail = this.tail.prev;
}
public void removeAtIndex(int index) throws AmishException
{
if (index == 0) {
Node q = head;
head = q.getNextNode();
}
else if ((index > numberOfElements - 1) || (index < 0))
System.out.println("Index out bounds.");
else {
Node currNode = head;
for (int i = 0; i < index; i++) {
currNode = currNode.getNextNode();
}
Node temp = currNode;
currNode = temp.getPrevNode();
currNode.setNextNode(temp.getNextNode());
temp = null;
numberOfElements--;
}
}
Node -
public class Node
{
private int payload;
private Node nextNode;
public Node prev;
public Node previous;
public Node next;
public Node(int payload)
{
this.payload = payload;
nextNode = null;
}
public Node getNextNode()
{
return this.nextNode;
}
public Node getPrevNode()
{
return this.getPrevNode();
}
public void setNextNode(Node n)
{
this.nextNode = n;
}
public void display()
{
System.out.print("(" + super.toString() + " : " + this.payload + ")");
if(this.nextNode != null)
{
System.out.print(" -> ");
this.nextNode.display();
}
else
{
System.out.println("");
}
}
public String toString()
{
return "" + super.toString() + " : " + this.payload;
}
public void setPrevNode(Node n)
{
previous = n;
}
}
Driver -
public class Driver
{
public static void main(String[] args) throws Exception
{
LinkedList ll = new LinkedList();
ll.addFront(7);
ll.addFront(5);
ll.addEnd(13);
ll.addEnd(27);
ll.addFront(2);
ll.addAtIndex(1, 0);
ll.addAtIndex(12, 6);
ll.addAtIndex(9, 2);
ll.addAtIndex(11, 2);
//ll.removeFront();
//ll.removeLast();
ll.removeAtIndex(1);
for(int i = 0; i < ll.length(); i++)
{
System.out.println(ll.get(i));
}
}
}
I got what I need to remove the head's index, but how to do anything else is beyond me.
I have the methods to remove the head and the tail now I just need to know how to remove at an index just Like if I were to add at an index.
Okay, completely editing this answer. I took your code and went from that. There were some issues with your Node class, check out mine. I created a barebones Node class, add the any other functionality you may need/want. For the LinkedList class, I created a simple add method that adds to the end of the list. Use this as a prototype for your other adds. Everything right now is working and I put some println's to help you see where the program is at. I highly recommend using a debugger. Also note that this is a doubly linked list.
Linked List
public class LinkedList {
private Node head;
private Node tail;
private int numberOfElements;
public LinkedList()
{
head = null;
tail = null;
numberOfElements = 0;
}
public int length()
{
return numberOfElements;
}
public void removeAtIndex(int index)
{
if (index == 0) {
Node q = head;
head = q.getNextNode();
numberOfElements--;
}
else if ((index > numberOfElements - 1) || (index < 0))
System.out.println("Index out of bounds.");
else {
Node currNode = head;
for (int i = 0; i < index; i++) {
//Node p = currNode;
System.out.println("At this payload " + currNode.getPayload());
currNode = currNode.getNextNode();
System.out.println("Now at this payload " + currNode.getPayload());
}
Node temp = currNode;
System.out.println("Removing the node with payload " + temp.getPayload());
currNode = temp.getPrevNode();
currNode.setNextNode(temp.getNextNode());
temp = null;
numberOfElements--;
}
}
public void add(int num) {
Node newNode = new Node(num);
newNode.setNextNode(null);
if (numberOfElements == 0) {
newNode.setPrevNode(null);
head = newNode;
tail = newNode;
}
else if (numberOfElements == 1) {
head.setNextNode(newNode);
tail = newNode;
tail.setPrevNode(head);
}
else {
newNode.setPrevNode(tail);
tail.setNextNode(newNode);
tail = newNode;
}
System.out.println("Inserted " + num + " into the linked list");
numberOfElements++;
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.println("Node with payload " + temp.getPayload());
temp = temp.getNextNode();
}
}
}
Node
public class Node {
private int payload;
private Node next;
private Node prev;
public Node(int payload) {
this.payload = payload;
prev = null;
next = null;
}
public Node getNextNode() {
return next;
}
public Node getPrevNode() {
return prev;
}
public void setNextNode(Node n) {
next = n;
}
public void setPrevNode(Node n) {
prev = n;
}
public int getPayload() {
return payload;
}
}
Driver
public class Driver {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(7);
ll.add(5);
ll.add(13);
ll.add(27);
ll.add(2);
ll.printList();
ll.removeAtIndex(3);
ll.printList();
}
}

Categories