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.
Related
I'm trying to construct a single linked list. The single linked list has a method, addLast, that adds a node to the tail of the linked list. I created a *LList2 *class to store the first and last node of the list.
The error occurs when I try to use the addLast method in the driver class. Below is my code. Any suggestions would be helpful!
`
// Part One Question 2,3
public class SingleLinkedListWorkSheetQ2Q3{
public static void main (String[] args){
ListNode<Integer> rear = new ListNode<>(0, null);
ListNode<Integer> list = new ListNode<>(1, rear);
list = new ListNode<>(2, list);
list = new ListNode<>(3, list);
LList2 <Integer> temp = new LList2 <> (list, rear);
temp.printWhile();
temp.addLast(new ListNode<Integer> (-2, null));
}
}
class ListNode <E> {
private E val;
private ListNode <E> next;
public ListNode(E val, ListNode <E> next){
this.val = val;
this.next = next;
}
public E getVal(){
return val;
}
public ListNode <E> getNext(){
return next;
}
public void updateNext(ListNode <E> node){
next = node;
}
}
class LList2 <E> {
private ListNode <E> front;
private ListNode <E> rear;
public LList2(ListNode <E> front, ListNode <E> rear){
this.front = front;
this.rear = rear;
}
public void printWhile(){
System.out.print("[");
while(front != null){
System.out.print(front.getVal() + ", ");
front = front.getNext();
}
System.out.print("]");
}
public void printFor(){
System.out.print("[");
for(ListNode <E> temp = front; temp != null; temp = temp.getNext()){
System.out.print(temp.getVal() + ", ");
}
System.out.print("]");
}
// obj represents value
public void addFirst(E obj){
front = new ListNode<E>(obj, front);
if(front.getNext() == null){
rear = front;
}
}
public void addLast(E obj){
if(rear != null)
rear.updateNext(new ListNode<E>(obj, null));
else{
rear = new ListNode<E>(obj, null);
front = rear;
}
}
}
`
Because you were using the Generic Types Java compiler will erase all E to the Integer type, so you can't set the ListNode<Integer>
the code will be this:
package com.github.lemon.office;
import joptsimple.internal.Strings;
public class SingleLinkedListWorkSheetQ2Q3 {
public static void main(String[] args) {
ListNode<Integer> rear = new ListNode<>(0, null);
ListNode<Integer> list = new ListNode<>(1, rear);
list = new ListNode<>(2, list);
list = new ListNode<>(3, list);
LList2<Integer> temp = new LList2<>(list, rear);
temp.printWhile();
temp.addLast(-2);
temp.printWhile();
}
}
class ListNode<E> {
private final E val;
private ListNode<E> next;
public ListNode(E val, ListNode<E> next) {
this.val = val;
this.next = next;
}
public E getVal() {
return val;
}
public ListNode<E> getNext() {
return next;
}
public boolean hasNext() {
return next != null;
}
public void updateNext(ListNode<E> node) {
next = node;
}
}
class LList2<E> {
private ListNode<E> front;
private ListNode<E> rear;
public LList2(ListNode<E> front, ListNode<E> rear) {
this.front = front;
this.rear = rear;
}
public void printWhile() {
StringBuilder sb = new StringBuilder("[");
for (ListNode<E> temp = front; temp != null; temp = temp.getNext()) {
sb.append(temp.getVal());
if (temp.hasNext()) {
sb.append(",");
}
}
sb.append("]");
System.out.println(sb);
}
public void printFor() {
System.out.print("[");
for (ListNode<E> temp = front; temp != null; temp = temp.getNext()) {
System.out.print(temp.getVal() + ", ");
}
System.out.print("]");
}
// obj represents value
public void addFirst(E obj) {
front = new ListNode<E>(obj, front);
if (front.getNext() == null) {
rear = front;
}
}
public void addLast(E obj) {
if (rear != null)
rear.updateNext(new ListNode<E>(obj, null));
else {
rear = new ListNode<E>(obj, null);
front = rear;
}
}
}
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
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.
I have created a doubly-linked list and implemented my own iterator.
However, I have done something wrong and my iterator results in endless loop.
Have been struggling to find the error, so any feedback is much appreciated. Thanks in advance. I apologise for the wall of code, I think the error lies within my iterator of the way I have created my Node class.
My Code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyDoubleEndedLinkedList<T extends Comparable<T>> implements
Iterable<T> {
// initialising Nodes including the two sentinal nodes
private Node<T> head;
private Node<T> tail;
private Node<T> current;
private int currentsize;
MyDoubleEndedLinkedList() {
head = new Node<T>();
tail = new Node<T>();
head.setNext(tail);
tail.setPrevious(head);
current = head;
currentsize = 0;
// Methods used to help loop and iterate through the list
public boolean isEmpty() {
return (current == head && current == tail);
}
public boolean endList() {
return (current != tail);
}
public void resetCurrent() {
current = head;
}
public void nextCurrent() {
current = current.getNext();
}
public T getCurrent() {
return current.getData();
}
public int size() {
return this.currentsize;
}
#Override
public Iterator<T> iterator() {
return new LinkedListIterator<T>();
}
// Node class for doublyLinkedList
public class Node<E> {
private Node<E> previous;
private Node<E> next;
private E data;
Node() {
previous = null;
next = null;
data = null;
}
Node(Node<E> newPrevious, Node<E> newNext, E newData) {
previous = newPrevious;
next = newNext;
data = newData;
}
// set previous node
public void setPrevious(Node<E> newPrevious) {
previous = newPrevious;
}
// set Next node
public void setNext(Node<E> newNext) {
next = newNext;
}
public void setData(E newData) {
data = newData;
}
public Node<E> getPrevious() {
return previous;
}
public Node<E> getNext() {
return next;
}
public E getData() {
return data;
}
}
class LinkedListIterator<E> implements Iterator<T> {
private Node<T> current;
private Node<T> previous;
private Node<T> previous2;
private boolean removeCalled;
public LinkedListIterator() {
current = head;
previous = null;
previous2 = null;
removeCalled = false;
}
public boolean hasNext() {
return (current != null);
}
public T next() {
if (hasNext()) {
T temp = current.getData();
previous2 = previous;
previous = current;
current = current.next;
removeCalled = false;
return temp;
}
throw new NoSuchElementException();
}
public void remove() {
if (previous == null || removeCalled) {
throw new IllegalStateException();
}
if (previous2 == null) {
head = current;
} else {
previous2.setNext(current);
previous = previous2;
}
removeCalled = true;
throw new UnsupportedOperationException();
}
}}
So i can't find the bug in your code but here is a simpler implementation of a basic linked list in Java. If you show me how you're adding elements to the list it would be easier to track down.
import java.util.Iterator;
public class MyLinkedList<T> implements Iterable<T> {
private Node head = null;
private Node tail = null;
public static void main(String[] args) {
MyLinkedList<String> li = new MyLinkedList<>();
li.add("1");
li.add("2");
li.add("3");
li.add("4");
li.add("5");
for (String s : li) {
System.out.println(s);
}
}
public void add(T data) {
if (head == null) {
head = new Node(data, null);
tail = head;
} else {
Node n = new Node(data, tail);
tail.next = n;
tail = n;
}
}
#Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
#Override
public boolean hasNext() {
return current != null;
}
#Override
public T next() {
T data = current.data;
current = current.next;
return data;
}
#Override
public void remove() {
}
};
}
class Node {
final T data;
Node prev = null;
Node next = null;
Node(T data, Node prev) {
this.data = data;
this.prev = prev;
}
}
}
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.