On my count method, i am trying to compare the object being sent with the object calling it, and I have no idea why i can not cal o.get(i) to get the value for Object o being passed. It tells me the method cannot be found even though i can call get(i) normally. Any ideas how i can get the value for the object getting passed so i can compare them?
public class GenericLinkedList<E> implements List<E> {
private class Node<E>{
private E data;
private Node<E> next;
}
private E data;
private Node<E> head = null;
private int size = 0;
private Node<E> nodeAt(int index){
Node<E> curNode = head;
int curIndex = 0;
while(curIndex < index){
curNode = curNode.next;
curIndex++;
}
return curNode;
}
#Override
public E get(int index) {
return nodeAt(index).data;
}
#Override
public void add(E value) {
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else{
Node<E> curNode = nodeAt(size - 1);
curNode.next = node;
}
size++;
}
public void add(int index, E value){
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else if(index == 0){
node.next = head;
head = node;
}else{
Node<E> curNode = nodeAt(index - 1);
node.next = curNode.next;
curNode.next = node;
}
size++;
}
#Override
public void remove(int index) {
if(index == 0){
head = head.next;
}else{
Node<E> curNode = nodeAt(index - 1);
curNode.next = curNode.next.next;
}
size--;
}
#Override
public void set(int index, E value) {
nodeAt(index).data = value;
}
public String toString(){
String s = "";
Node<E> curNode = head;
s += curNode.data +" -> ";
while(curNode.next != null){
curNode = curNode.next;
s += curNode.data +" -> ";
}
s += "null";
return s;
}
public void clear() {
for (int i = 0; i < size; i++)
set(i, null);
size = 0;
}
#Override
public void removeAll(E o)//Clears out the array object by setting everything to null
{
for(int i = 0; i < this.size; i++)
{
}
}
#Override
public int count(Object o)
{
System.out.println(o);
int count = 0;
for(int i = 0; i< size;i++)
{
if(get(i) == o.get(i))
{
count++;
}
}
return count;
/*int count = 0;
for(int i = 0;i<this.size;i++)
{
for(int j = 0;i<size;j++)
{
}
}
return count;*/
}
public void reverse()
{
int x = size;
for(int i = 0; i < this.size; i++)
{
E temp = this.get(x);
this.set(x, get(i));
this.set(i, temp);
x++;
}
}
public Object subList(int beginIndex, int endIndex)
{
int j = 0;
GenericLinkedList<E> LinkedList = new GenericLinkedList<E>();
if(beginIndex == endIndex)
return LinkedList;
else if(beginIndex > endIndex||endIndex>size||beginIndex<0)
{
return null;
}
else
{
for(int i = beginIndex; i <= endIndex;i++)
{
LinkedList.add(get(i));
j++;
}
}
return LinkedList;
}
public static void main(String[] args) {
GenericLinkedList<Integer> myList = new GenericLinkedList<Integer>();
myList.add(4);
myList.add(7);
myList.add(123123);
System.out.println(myList.get(2));
GenericLinkedList<Integer> myList2 = new GenericLinkedList<Integer>();
myList2.add(4);
myList2.add(7);
myList2.add(8);
myList2.add(3,999);
System.out.println(myList2);
System.out.println(myList.count(myList2));
//System.out.println(myList2);
// myList2.clear();//Testing our clear class
// System.out.println(myList2);
//System.out.println(myList2.subList(1, 3));//Testing our clear class
// System.out.println(myList2);
}
}
You have a problem when trying to call o.get() because it is an object of the base type Object which has no method get defined. To get the proper result you have two possible solutions....
The short solution is to type cast.
((GenericLinkedList<Object>)o).get(i)
Or a more easily readable solution is to change the signature of your count method:
public int count(GenericLinkList<E> list) {
...
}
Change your count method to public int GenericLinkedList(Object o)
If you use Object as the type of the parameter, you can only call the methods which are available on Object.
Related
import java.util.*;
public class ListStack extends LinkedList{
public ListStack() { // <== constructor, different from ListStackComp.java
super();
}
public boolean empty() {
if(isEmpty()){
return true;
}else{
return false;
}
}
public Object push(Object item) {
addToHead(item);
return item;
}
public Object pop() {
Object item = removeFromHead();
return item;
}
public Object peek() {
Object item = get(0);
return item;
}
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 0;i<length;i++){
if(item.equals(current.getData())){
num = i;
}
else{
current = current.getNext();
}
}
return num;
}
}
The result is:
[ 789.123 E Patrick 123 Dog Cat B A ]
peek() returns: 789.123
Patrick is at 7
A is at 7
789.123 is at 7
Peter is at -1
Can help me to solve the problem? Does search() have some error?
class ListNode {
private Object data;
private ListNode next;
ListNode(Object o) { data = o; next = null; }
ListNode(Object o, ListNode nextNode)
{ data = o; next = nextNode; }
public void setData(Object data){
this.data = data;
}
public void setNext(ListNode next){
this.next = next;
}
public Object getData() { return data; }
public ListNode getNext() { return next; }
} // class ListNode
class EmptyListException extends RuntimeException {
public EmptyListException () { super ("List is empty"); }
} // class EmptyListException
class LinkedList {
protected ListNode head; // <== chnage to protected for inheriting
protected ListNode tail; // <== change to protected for inheriting
protected int length; // the length of the list <== chnage to protected for inheriting
public LinkedList() {
head = tail = null;
length = 0;
}
public boolean isEmpty() { return head == null; }
public void addToHead(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else
head = new ListNode(item, head);
length++;
}
public void addToTail(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else {
tail.setNext(new ListNode(item));
tail = tail.getNext();
}
length++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = head.getData();
if (head == tail)
head = tail = null;
else
head = head.getNext();
length--;
return item;
}
public Object removeFromTail() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = tail.getData();
if (head == tail)
head = tail = null;
else {
ListNode current = head;
while (current.getNext() != tail)
current = current.getNext();
tail = current;
current.setNext(null);
}
length--;
return item;
}
public String toString() {
String str = "[ ";
ListNode current = head;
while (current != null) {
str = str + current.getData() + " ";
current = current.getNext();
}
return str + " ]";
}
public int count() {
return length;
}
public Object remove(int n) {
Object item = null;
if (n <= length) { // make sure there is nth node to remove
// special treatment for first and last nodes
if (n == 1) return removeFromHead();
if (n == length) return removeFromTail();
// removal of nth node which has nodes in front and behind
ListNode current = head;
ListNode previous = null;
for (int i = 1; i < n; i++) { // current will point to nth node
previous = current;
current = current.getNext();
}
// data to be returned
item = current.getData();
// remove the node by adjusting two pointers (object reference)
previous.setNext(current.getNext());
}
length--;
return item;
}
public void add(int n, Object item) {
// special treatment for insert as first node
if (n == 1) {
addToHead(item);
return;
}
// special treatment for insert as last node
if (n > length) {
addToTail(item);
return;
}
// locate the n-1th node
ListNode current = head;
for (int i = 1; i < n-1; i++) // current will point to n-1th node
current = current.getNext();
// create new node and insert at nth position
current.setNext(new ListNode(item, current.getNext()));
length++;
}
public Object get(int n) {
// n is too big, no item can be returned
if (length < n) return null;
// locate the nth node
ListNode current = head;
for (int i = 1; i < n; i++)
current = current.getNext();
return current.getData();
}
} // class LinkedList
import java.util.Stack;
import java.util.Iterator;
public class TestStack {
public static void main (String args[]) {
ListStack s = new ListStack();
System.out.println(s);
System.out.println("Patrick is at " + s.search("Patrick"));
s.push(new Character('A'));
System.out.println(s);
s.push(new Character('B'));
System.out.println(s);
s.push("Cat");
System.out.println(s);
s.push("Dog");
System.out.println(s);
s.push(new Integer(123));
System.out.println(s);
s.push("Patrick");
System.out.println(s);
s.push(new Character('E'));
System.out.println(s);
s.push(new Double(789.123));
System.out.println(s);
System.out.println("peek() returns: " + s.peek());
System.out.println("Patrick is at " + s.search("Patrick"));
System.out.println("A is at " + s.search(new Character('A')));
System.out.println("789.123 is at " + s.search(new Double(789.123)));
System.out.println("Peter is at " + s.search("Peter"));
System.out.println();
}
} // class TestStack
There is another code of LinkedList and Test file
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 0;i<length;i++){
if(item.equals(current.getData())){
return i;
}
else{
current = current.getNext();
}
}
return num;
}
Hope It will work.
public Object peek() {
Object item = get(0);
return item;
}
public int search(Object item) {
ListNode current = head;
int num=-1;
for(int i = 1;i<length;i++){
if(item.equals(current.getData())){
num = i;
return num;
}
else{
current = current.getNext();
}
}
return num;
}
There is new problem in the result:
[ A B Cat Dog 123 Patrick E 789.123 ]
peek() returns: A
Patrick is at 6
A is at 1
789.123 is at -1
Peter is at -1
Why the result cannot find 789.123?
The peek() method how can I improve that can find 789.123 is top?
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));
}
}
Here is my code, but I keep getting the "Note: LinkedListAdd.java uses unchecked or unsafe operations." I'm trying to do what I can to get rid of it, but nothing seems to be working. The base class compiles fine and has no warning, and the check seems to be coming from the add all method. Any ideas?
public class LinkedListAdd<E extends Comparable <E> > extends LinkedList<E>
{
public LinkedListAdd()
{
super();
}
public <E extends Comparable<E> > boolean addAll(final int index, final E[] array)
{
if(index < 0 || index > this.size())
throw new IndexOutOfBoundsException("Index out of bounds");
if(array == null)
throw new NullPointerException("Null array");
Node nn = null;
for(int y = array.length - 1; y >= 0; y--)
{
nn = new Node(array[y], null);
if(this.size() == 0)
{
this.head.next = nn;
this.size += 1;
}
else
{
Node cur = this.head.next, prev = null;
for(int x = 0; x < index; x++)
{
prev = cur;
cur = cur.next;
}
if(prev == null)
{
nn.next = cur;
this.head.next = nn;
this.size += 1;
}
else
{
prev.next = nn;
nn.next = cur;
this.size += 1;
}
}
}
if(nn == null)
return false;
return true;
}
}//end class LinkedListSort
Here is the base class
public class LinkedList<E extends Comparable <E> >
{
protected static class Node<E extends Comparable <E> >
{
public E data;
public Node<E> next;
public Node()
{
this.next = null;
this.data = null;
}// end DVC
public Node(final E data, final Node<E> next)
{
this.next = next;
this.data = data;
}// end EVC
}// end class Node
protected Node <E> head;
protected int size;
public LinkedList()
{
this.head = new Node<>();
this.size = 0;
}
public void clear()
{
this.head = null;
this.size = 0;
}// end clear
public int size(){return this.size;}
public void addFirst(final E data)
{
this.head.next = new Node<>(data, this.head.next);
size ++;
}// end
public String toString()
{
String temp = "List size: " + this.size;
if(this.head.next == null)
return temp += "\nEmpty List";
else
{
temp += "\n";
Node<E> cur = head.next;
while(cur != null)
{
temp += cur.data + " ";
cur = cur.next;
}
return temp;
}// end else
}// end toString
}// end class
There's a couple of things I'd recommend doing; firstly I'd add methods for get/set on your head/next/size/data and make those fields private
With regards to your generics;
the method signature should be
public boolean addAll(final int index, final E[] array)
and your declarations for nodes in that method need to be
Node<E> node
I'm writing this code to implement a stack as a linked list but I keep getting an error when I compile this part of the code and can't figure out why
I definitely know that it shouldn't be giving me this error since there are enough brackets and none of them are out of place I hope
The Error:
C:\Users\Michelle\Desktop\ITB\Semester 5\Data Structures & Algorithms\Assignment\ListReference.java:108: error: reached end of file while parsing
}
^
1 error
My Code:
public class ListReference implements StackInterface {
private Node top;
//private Object item;
private int NumItems;
public ListReference() {
NumItems = 0;
top = new Node(null);
}
public boolean isEmpty() {
return NumItems == 0;
}
public int size() {
return NumItems;
}
/*public Node find(int index) {
Node curr = tail;
for(int skip = 1; skip < index; skip++) {
curr.getNext();
}
return curr;
}*/
public Object get(int index) {
if(index <= 0)
return null;
Node ListReference = top.getNext();
for(int i=1; i < index; i++) {
if (ListReference.getNext() == null)
return null;
ListReference = ListReference.getData();
}
}
public void add(int index, Object item) {
Node ListReferenceTemp = new Node(item);
Node ListRefCurr = top;
while(ListRefCurr.getNext() != null) {
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListReferenceTemp);
NumItems++;
}
public void add(Object data) {
Node ListReferenceTemp = new Node(item);
Node ListRefernce = top;
for(int i=1; i < index && ListReference.getNext() != null; i++) {
ListReference = ListReference.getNext();
}
ListReferenceTemp.setNext(ListReference.getNext());
ListReference.setNext(ListReferenceTemp);
NumItems++;
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node ListRefCurr = top;
for (int i = 1; i < index; i++) {
if (ListRefCurr.getNext() == null) {
return false;
}
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListRefCurr.getNext().getNext());
NumItems--; // decrement the number of elements variable
return true;
}
public String toString() {
Node ListReference = top.getNext();
String output = "";
while (ListREference != null) {
output += "[" + ListRefCurr.getData().toString() + "]";
ListRefCurr = ListRefCurr.getNext();
}
return output;
}
I must create Stack by using Linked List. Here is my LinkedList class:
package stack;
import java.util.EmptyStackException;
public class List {
Element head;
int size = 0;
public void Add(Object value) {
if (size == 0) {
head = new Element(value);
size++;
return;
}
Insert(size, value);
}
public void Insert(int index, Object value) {
if (index > size) {
throw new IndexOutOfBoundsException("Bad index");
}
Element tmp = head;
for (int i = 0; i < index -1 ; i++) {
tmp = tmp.next;
}
Element newElement = new Element(value);
newElement.next = tmp.next;
tmp.next = newElement;
size++;
}
public int Size() {
return size;
}
public Object Get(int index) {
if (index > size - 1) {
throw new IndexOutOfBoundsException("Index doesn't exist");
}
Element tmp = head;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
System.out.println(tmp.value.toString());
return tmp;
}
public Object Set(int index, Object value) {
if (index > size - 1) {
throw new IndexOutOfBoundsException("Index doesn't exist");
}
Element tmp = head;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
Element returnValue = new Element(value);
returnValue = tmp;
tmp.value = value;
return returnValue;
}
public Object Delete(int index) {
Element tmp;
tmp = head;
for (int i = 0; i < index - 1; i++) {
tmp = tmp.next;
}
Element returnValue;
returnValue = tmp;
head = tmp.next;
size--;
return returnValue;
}
public boolean Contains(Object value) {
Element tmp = head;
for (int i = 0; i < size - 1; i++) {
tmp = tmp.next;
if (tmp.value == value) {
System.out.println("true");
return true;
}
}
System.out.println("False");
return false;
}
public boolean IsEmpty() {
return Size() > 0;
}
public void Clear() {
size = 0;
}
public void Display() throws EmptyStackException {
if (size <= 0) {
throw new EmptyStackException();
}
Element tmp = head;
for (int i = 0; i < size; i++) {
System.out.println(tmp.value.toString());
tmp = tmp.next;
}
}
}
and i got Stack interface
public interface IStack {
public interface Stack {
public void push(Object value); // odłóż na stos
public Object pop() throws EmptyStackException; //pobierz ze stosu
public Object peek() throws EmptyStackException; //odczytaj ze stosu,
// and some others
Any1 have am idea how to create pop method?
LinkedList is already a stack, it has pop, push and peek methods. Just create an adapter class and use those methods