Add Integer into LInked List
I am trying to re-study several subjects on data structure inlcuding
Linked List. Because it's been too long since my last class works,
unfortunately, I am not sure what I am doing wrong with my code. Please
give me some advice how to resolve this problem as shown below.
LinkedList.java
package my.linked.list;
public class LinkedList<E> {
private Listnode<E> items;
private Listnode<E> lastNode;
int numItems;
public LinkedList() {
items = new Listnode<E>(null);
lastNode = new Listnode<E>(null);
numItems = 0;
}
public void add(E d) {
//Listnode<E> temp = new Listnode<E>(d);
//lastNode.setNext(temp);
lastNode.setNext(new Listnode<E>(d));
lastNode = lastNode.getNext();
numItems++;
}
//public void add(int pos){
//
//}
public void remove(Listnode<E> n) {
Listnode<E> temp = items;
if (items == n) {
items = n.getNext();
}
while (temp.getNext() != n) {
temp = temp.getNext();
}
temp.setNext((n.getNext()));
numItems--;
}
//public void remove(int pos) {
//
//}
public boolean isEmpty() {
boolean ans = false;
if (numItems == 0) {
ans = true;
}
return ans;
}
public boolean contains() {
return false;
}
public int size() {
return numItems;
}
}
MyLinkedListTest.java
package my.linked.list;
import java.io.*;
public class MyLinkedListTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList myTest = new LinkedList();
// check whether the linkedlist is empty or not
boolean ans = false;
ans = myTest.isEmpty();
if (ans = true) {
System.out.println("This Linked List is empty");
} else {
System.out.println("This Linked List is not empty");
}
// add operation
for (int i=0; i<5; i++){
myTest.add(i);
System.out.println(myTest);
}
System.out.println("Current size of myList : " + myTest.size());
}
}
When I run this code, I receive messages below.
This Linked List is empty
my.linked.list.LinkedList@667262b6
my.linked.list.LinkedList@667262b6
my.linked.list.LinkedList@667262b6
my.linked.list.LinkedList@667262b6
my.linked.list.LinkedList@667262b6
Current size of myList : 5
It looks like that my code doesn't add integer values into the linkedlist
data type. Please let me know how to resolve this problem. Thanks so much
in advance.
No comments:
Post a Comment