Java: How to reverse over an Iterable - java

I have to reverse a Linked List. Just look at the Method reverse, maybe you could help me because I am desperate ;). Maybe it's doable with the methods below...
Thank you Everyone.
Heres the Code:
import java.util.Iterator;
public class LL<E> implements Iterable<E> {
E head;
LL<E> tail;
String a="[";
public LL(E head, LL<E> tail) {
super();
this.head = head;
this.tail = tail;
}
public LL() {
this(null, null);
}
boolean isEmpty() {
return head == null && tail == null;
}
#Override
public Iterator<E> iterator() {
return new MyIterator(this);
}
private class MyIterator implements Iterator<E> {
LL<E> current;
public MyIterator(LL<E> current) {
super();
this.current = current;
}
#Override
public boolean hasNext() {
return !current.isEmpty();
}
#Override
public E next() {
E result = current.head;
current = current.tail;
return result;
}
E get(int i) throws IndexOutOfBoundsException{//maybe...
E result = current.head;
for(int q=0; q<i;q++){
current=current.tail;
}
return result;
}
boolean contains(E e){//das gleiche nur mit tail
boolean yo=false;
while(hasNext()){
E result= current.head;// oder tail
if(result.equals(e))return yo=true;//unnötig ;)
}
return yo;
}
E last(){//oder nochmal
E result=get(1);
if(hasNext()) {result= next();};
return result;
}
}
public LL<E> limit(int i){
if(i>0&& !isEmpty()){
return new LL<E>(head,tail.limit(i-1));
}
return new LL<E>();
}
public LL<E> drop(int i){
//löschen wie bei limit
if(i>0){
return tail.drop(i-1);
}
return new LL<E>(head,tail);
}
public LL<E> sublist(int from, int to){
//was rauslöschen und limit
LL<E> ersteElemente= this.limit(to);
//erste delete
return ersteElemente.drop(from);
}
public LL<E> reverse(){
//2 schleifen
for(int q=6;q>0;q--){
return this.sublist(q-1, q);
}
}
#Override
public String toString(){
String result="[";
LL<E> n;//for Schleife
//while (tail!=null){
this.forEach((x)-> a+=x+";");
a+="]";
//}
return a;
}
public static void main(String[] args) {
LL<String> xs = new LL<>("Freunde", new LL<>("Römer", new LL<>("Landsleute",
new LL<>("leiht", new LL<>("mir", new LL<>("euer", new LL<>("Ohr", new LL<>())))))));
xs.forEach((x) -> System.out.println(x.toUpperCase()));
for (String x:xs){
System.out.println(x.toUpperCase());
}
System.out.println((xs.toString()));
xs.toString();
System.out.println("END");
}
}

You need to return a value in reverse method
public LL<E> reverse() {
LL<E> result = null;
// 2 schleifen
for (int q = 6; q > 0; q--) {
result = this.sublist(q - 1, q);
}
return result;
}

Related

How to extend child classes with a parent interface class

interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?

raw type error occuring where no raw types are used

Here is a link-based Stack class.
import java.util.Iterator;
public class LStack<T>
{
private Link top;
private int size;
public LStack()
{
top = null;
size = 0;
}
#Override
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("[");
for(Link nav = top; nav != null; nav=nav.getNext())
{
sb.append(nav.getDatum());
if(nav.getNext() != null)
{
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public void push(T newItem)
{
top = new Link(newItem, top);
size++;
}
public T pop()
{
if(isEmpty())
{
throw new EmptyStackException();
}
size--;
T out = top.getDatum();
top = top.getNext();
return out;
}
public T peek()
{
if(isEmpty())
{
throw new EmptyStackException();
}
return top.getDatum();
}
public void clear()
{
top = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return top == null;
}
public Iterator<T> iterator()
{
return new LStackIterator();
}
/********************aliens*******************/
class LStackIterator implements Iterator<T>
{
private Link current;
public LStackIterator()
{
current = top;
}
public T next()
{
T out = current.getDatum();
current = current.getNext();
return out;
}
public boolean hasNext()
{
return current.getNext() != null;
}
}
public static void main(String[] args)
{
LStack<String> elStack = new LStack<>();
elStack.push("A");
elStack.push("B");
elStack.push("C");
elStack.push("D");
for(String quack: elStack)
{
System.out.println(quack);
}
System.out.printf("The size is %d\n", elStack.size());
System.out.println(elStack);
System.out.println(elStack.pop());
System.out.println(elStack.pop());
System.out.println(elStack.pop());
System.out.println(elStack.pop());
System.out.println(elStack);
}
class Link
{
private T datum;
private Link next;
public Link(T datum, Link next)
{
this.datum = datum;
this.next = next;
}
public Link(T datum)
{
this(datum, null);
}
public T getDatum()
{
return datum;
}
public Link getNext()
{
return next;
}
}
}
I then try to run and get this.
$ javac LStack.java
LStack.java:95: error: incompatible types: Object cannot be converted to String
for(String quack: elStack)
^
1 error
What is happening here? Changing the type from String to Object causes it to work, but I am not using any raw types.
You must implement Iterable for "For-Each" loop
public class LStack<T> implements Iterable<T>

How is this possible? (Junit exception testing of linked list implementation

I am writing a LinkedList implementation which includes a previous function that returns the position prior to the one passed as an input argument. It should check whether the inputted position is the first one and throw an exception in that case:
#Override
public Position<T> previous (Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
However, the following test is failing because it isn't throwing the expected exception from trying to use the previous function on the first position in the array:
#Test (expected=PositionException.class)
public void gettingPreviousAtFront() {
Position<String> one = list.insertFront("One");
Position<String> two = list.insertFront("Two");
assertTrue(list.first(two));
Position<String> beforeTwo = list.previous(two);
}
There was 1 failure: 1)
gettingPreviousAtFront(hw6.test.LinkedListTest)
java.lang.AssertionError: Expected exception:
exceptions.PositionException at
org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
It is even passing the assertion on line 301 of the test that "two" is first. So how is it possible that the exception is not being thrown by the previous function?
Here is the full linkedlist code:
package hw6;
import exceptions.EmptyException;
import exceptions.PositionException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements List<T> {
private static final class Node<T> implements Position<T> {
// The usual doubly-linked list stuff.
Node<T> next; // reference to the Node after this
Node<T> prev; // reference to the Node before this
T data;
// List that created this node, to validate positions.
List<T> owner;
#Override
public T get() {
return this.data;
}
#Override
public void put(T t) {
this.data = t;
}
}
/** This iterator can be used to create either a forward
iterator, or a backwards one.
*/
private final class ListIterator implements Iterator<T> {
Node<T> current;
boolean forward;
ListIterator(boolean f) {
this.forward = f;
if (this.forward) {
this.current = LinkedList.this.sentinelHead.next;
} else {
this.current = LinkedList.this.sentinelTail.prev;
}
}
#Override
public T next() throws NoSuchElementException {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
T t = this.current.get();
if (this.forward) {
this.current = this.current.next;
} else {
this.current = this.current.prev;
}
return t;
}
#Override
public boolean hasNext() {
if (this.forward) {
return this.current != LinkedList.this.sentinelTail;
}
else {
return this.current != LinkedList.this.sentinelHead;
}
}
}
/* ** LinkedList instance variables are declared here! ** */
private Node<T> sentinelHead;
private Node<T> sentinelTail;
private int length; // how many nodes in the list
/**
* Create an empty list.
*/
public LinkedList() {
this.sentinelHead = new Node<>();
this.sentinelTail = new Node<>();
this.sentinelHead.owner = this;
this.sentinelTail.owner = this;
this.sentinelTail.prev = this.sentinelHead;
this.sentinelHead.next = this.sentinelTail;
this.length = 0;
}
// Convert a position back into a node. Guards against null positions,
// positions from other data structures, and positions that belong to
// other LinkedList objects. That about covers it?
private Node<T> convert(Position<T> p) throws PositionException {
try {
Node<T> n = (Node<T>) p;
if (n.owner != this) {
throw new PositionException();
}
return n;
} catch (NullPointerException | ClassCastException e) {
throw new PositionException();
}
}
#Override
public boolean empty() {
return this.length == 0;
}
#Override
public int length() {
return this.length;
}
#Override
public boolean first(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelHead.next == n;
}
#Override
public boolean last(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelTail.prev == n;
}
#Override
public Position<T> front() throws EmptyException {
if (this.length == 0) {
throw new EmptyException();
}
return this.sentinelHead.next;
}
#Override
public Position<T> back() throws EmptyException {
if (this.empty()) {
throw new EmptyException();
}
return this.sentinelTail.prev;
}
#Override
public Position<T> next(Position<T> p) throws PositionException {
if (this.last(p)) {
throw new PositionException();
}
return this.convert(p).next;
}
#Override
public Position<T> previous(Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
#Override
public Position<T> insertFront(T t) {
return this.insertAfter(this.sentinelHead, t);
}
#Override
public Position<T> insertBack(T t) {
return this.insertBefore(this.sentinelTail, t);
}
#Override
public void removeFront() throws EmptyException {
this.remove(this.front());
}
#Override
public void removeBack() throws EmptyException {
this.remove(this.back());
}
#Override
public void remove(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
n.owner = null;
n.prev.next = n.next;
n.next.prev = n.prev;
this.length--;
}
#Override
public Position<T> insertBefore(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.prev = current.prev;
current.prev.next = n;
n.next = current;
current.prev = n;
this.length++;
return n;
}
#Override
public Position<T> insertAfter(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.next = current.next;
current.next.prev = n;
n.prev = current;
current.next = n;
this.length++;
return n;
}
#Override
public Iterator<T> forward() {
return new ListIterator(true);
}
#Override
public Iterator<T> backward() {
return new ListIterator(false);
}
#Override
public Iterator<T> iterator() {
return this.forward();
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[");
for (Node<T> n = this.sentinelHead.next; n != this.sentinelTail; n = n.next) {
s.append(n.data);
if (n.next != this.sentinelTail) {
s.append(", ");
}
}
s.append("]");
return s.toString();
}
}

LinkedList - delete(Object) method works strange - deleting last element doesn't work properly

I have LinkedList with test program. As you can see in that program I add some Students to the list. I can delete them. If I choose s1,s2,s3 oraz s4 to delete everything runs well, and my list is printed properly and information about number of elements is proper. But if I delete last element (in this situation - s5) info about number of elements is still correct, but this element is still printed. Why is that so? Where is my mistake?
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public void clear(){
head.setNext(null);
size=0;
}
public void add(Object value){
if (head.getNext()==null) head.setNext(new Element(value));
else {
Element last = head.getNext();
//wyszukiwanie ostatniego elementu
while(last.getNext() != null)
last=last.getNext();
// i ustawianie jego referencji next na nowowstawiany Element
last.setNext(new Element(value));}
++size;
}
public Object get(int index) throws IndexOutOfBoundsException{
if(index<0 || index>size) throw new IndexOutOfBoundsException();
Element particular = head.getNext();
for(int i=0; i <= index; i++)
particular = particular.getNext();
return particular.getValue();
}
public boolean delete(Object o){
if(head.getNext() == null) return false;
if(head.getNext().getValue().equals(o)){
head.setNext(head.getNext().getNext());
size--;
return true;
}
Element delete = head.getNext();
while(delete != null && delete.getNext() != null){
if(delete.getNext().getValue().equals(o)){
delete.setNext(delete.getNext().getNext());
size--;
return true;
}
delete = delete.getNext();
}
return false;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
public void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
public Element(Object value){
setValue(value);
}
public void setValue(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
//ustawia referencję this.next na obiekt next podany w atgumencie
public void setNext(Element next) {
if (next != null)
this.next = next;
}
public Element getNext(){
return next;
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public boolean isDone() {
return current == null;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista = new Lista();
Iterator iterator = lista.iterator();
Student s1 = new Student("Kowalski", 3523);
Student s2 = new Student("Polański", 45612);
Student s3 = new Student("Karzeł", 8795);
Student s4 = new Student("Pałka", 3218);
Student s5 = new Student("Konowałek", 8432);
Student s6 = new Student("Kłopotek", 6743);
Student s7 = new Student("Ciołek", 14124);
lista.add(s1);
lista.add(s2);
lista.add(s3);
lista.add(s4);
lista.add(s5);
lista.wyswietlListe();
lista.delete(s5);
lista.wyswietlListe();
lista.infoOStanie();
lista.clear();
lista.infoOStanie();
}
}
The problem is that your setNext(Element next) method does not set anything if next == null. And that is the case for the last element of your list.
So when you call delete.setNext(delete.getNext().getNext());, nothing is actually set because delete.getNext().getNext() is null!
Remove the if (next != null) condition in setNext and it will work.

Type Syntax error on token(s), misplaced construct(s)

package list;
public class LinkedList implements List {
//Datenfeld
private Element item;
//Zeigerfeld
private LinkedList next;
//Konstruktor, erzeugt leere Liste
public LinkedList() {
item = null;
next = null;
}
//Selektoren
public Object getItem() {
return item;
}
public LinkedList next() {
return next;
}
//ist die Liste leer?
public boolean isEmpty() {
return next == null;
}
public Object firstElement() {
if (isEmpty())
return null;
else
return next.item;
}
public int length() {
if (isEmpty())
return 0;
else
return 1 + next.length();
}
//fügt x am Kopf ein
public LinkedList insert(Element x) {
LinkedList l = new LinkedList();
l.item = x;
l.next = next;
next = l;
return this;
}
//hängt das x ans Ende der Liste und liefert Teilliste
public LinkedList append (Element x) {
if (isEmpty())
return insert(x);
else
return next.append(x);
}
//liefert Null, falls x nicht in Liste
//sonst Teilliste
private LinkedList find(Element x) {
if (isEmpty())
return null;
else
if (firstElement().equals(x))
return this;
else
return next.find(x);
}
//entfertn erstes x der Liste
public LinkedList delete(Element x) {
LinkedList l = find(x);
if (l != null)
return l.next = l.next.next;
else
return this;
}
//entfernt das erste Element der Liste
public LinkedList delete() {
if (!isEmpty())
next = next.next;
return this;
}
public boolean isInList(Element x) {
return(find(x) != null);
}
public String toString() {
return (next == null ? " |--" : " --> " + next.item + next);
}
static void println(Element x) {
System.out.println(x.toString());
}
public LinkedList add(Element x, int n) {
return null;
}
public LinkedList remove(int n) {
return null;
}
public Element get(int n) {
return null;
}
public int firstIndexOf(Element x) {
return 1;
}
public int lastIndexOf(Element x) {
return 1;
}
LinkedList l1 = new LinkedList();
l1.insert("AA");
}
In the last line (l1.insert("AA"); I get the error
Type Syntax error on token(s), misplaced construct(s).
Need help. Can't find the problem.
You can't have random statements like that outside of methods. You need to put that statement in a method, or build a class that uses your linked lists and does that insert.

Categories

Resources