I am trying to Implement a Linked List Using Java.
The code I have used is as follow
public class LinkNode
{
private int data;
public LinkNode next;
public LinkNode (int data)
{
this.data = data;
}
public void setData(int data)
{
this.data = data;
}
public int getData()
{
return this.data;
}
public void setNext(LinkNode next)
{
this.next = next;
}
public LinkNode getNext()
{
return this.next;
}
public static void main (String [] args)
{
LinkNode Node1 = new LinkNode(3);
LinkNode Head = Node1;
LinkNode Node2 = new LinkNode(4);
LinkNode Node3 = new LinkNode(5);
LinkNode Node4 = new LinkNode(6);
Head.setNext(Node1);
Node1.setNext(Node2);
Node2.setNext(Node3);
Node3.setNext(Node4);
int iCounter =0;
LinkNode currentNode= Head;
while (currentNode.getNext()!=null)
{
int data = currentNode.getData();
System.out.println(data);
currentNode = currentNode.getNext();
iCounter=iCounter+1;
}
System.out.println("No Of Nodes are"+iCounter);
}
}
The Problem here I am getting No of Nodes 3
The code is not counting the last Node that is Node4.
The out put is as follow
3
4
5
No Of Nodes are3
Please let me know what is the problem in the code.
To make Head point to Node1 write
Head = Node1;
If you write Head=null it means that Head doesn't point to any node, and you get a null pointer exception because you then try to get the next node from a node that doesn't exist.
The second problem is that you exit the loop when currentNode.getNext() returns null. The getNext() method returns null when you have reached the last node of the list; if you exit the loop then you won't count the last node. Change the loop condition into:
while (currentNode != null)
And please don't edit the question to ask followup questions. Nobody is notified when a question is edited, so you won't get new answers. It also makes the site less useful for future visitors. Post a new "question" for each question that you have.
Head, should not be null. Instead the data in head should be null, otherwise you have no way to find next.
Here is implementation of Singly Linked List I've developed years ago:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* #author sergiizagriichuk
*/
public class Node<T> {
private T value;
private Node<T> next;
public Node(T value) {
this.value = value;
}
public static <T> Node<T> createLinkedListFromArray(T... array) {
if (checkIfArrayIsNullOrEmpty(array)) return new Node<T>(null);
Node<T> head = new Node<T>(array[0]);
createLinkedList(array, head);
return head;
}
private static <T> boolean checkIfArrayIsNullOrEmpty(T[] array) {
return array == null || array.length == 0;
}
private static <T> void createLinkedList(T[] array, Node<T> head) {
Node<T> node = head;
for (int index = 1; index < array.length; index++) {
T t = array[index];
node.setNext(new Node<T>(t));
node = node.getNext();
}
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return value != null && value.equals(node.value);
}
#Override
public int hashCode() {
return value.hashCode();
}
#Override
public String toString() {
List ret = createList();
return Arrays.toString(ret.toArray());
}
private List createList() {
Node root = this;
List ret = new ArrayList();
while (root != null) {
ret.add(root.getValue());
root = root.getNext();
}
return ret;
}
}
And some Tests:
/**
* #author sergiizagriichuk
*/
public class NodeTest {
#Test
public void testCreateList() throws Exception {
Node<Integer> node = Node.createLinkedListFromArray(1, 2, 3, 4, 5);
Assert.assertEquals(Integer.valueOf(1), node.getValue());
Assert.assertEquals(Integer.valueOf(2), node.getNext().getValue());
}
#Test
public void testCreateListSize() throws Exception {
Integer[] values = new Integer[]{1, 2, 3, 4, 5};
int size = values.length - 1;
Node<Integer> node = Node.createLinkedListFromArray(values);
int count = 0;
while (node.getNext() != null) {
count++;
node = node.getNext();
}
Assert.assertEquals(size, count);
}
#Test
public void testNullNode() throws Exception {
Node<Integer> nullNode = new Node<Integer>(null);
assertNullNode(nullNode);
}
#Test
public void testNullArray() throws Exception {
Node<Integer> nullArrayNode = Node.createLinkedListFromArray();
assertNullNode(nullArrayNode);
}
#Test
public void testSetValue() throws Exception {
Node<Integer> node = new Node<Integer>(null);
assertNullNode(node);
node.setValue(1);
Assert.assertEquals(Integer.valueOf(1), node.getValue());
}
private void assertNullNode(Node<Integer> nullNode) {
Assert.assertNotNull(nullNode);
Assert.assertNull(nullNode.getValue());
}
}
Try to use or redevelop for your situation
Related
I was working on a program to add nodes to a list, but I seem to be doing something wrong...
My java program has three Classes; Demo, Lista and Node
Class Node:
public class Node {
private int num;
private Node tail;
private Node head;
public Node (int num, Node head, Node tail) {
this.num = num;
this.head = head;
this.tail = tail;
}
}
Class Lista:
public class Lista {
private Node nil;
public Lista () {
nil = null;
}
public void add (int num) {
Node newNode = new Node(num, head, tail);
if (head == null) {
head = newNode;
tail = newNode;
}
}
public void display () {
Node current = head;
while(current != null) {
System.out.print(current.num);
}
}
}
Class Demo:
public class Demo {
public static void main ( String [] args) {
Lista lista = new Lista();
lista.add(3);
lista.add(9);
lista.add(7);
lista.display();
}
}
Demo class is to add the different nodes to the list "lista". Class Node has num, head which is the next one and tail which is the previous one. How can I go about getting Class Lista to be able to use head and tail from Class Node? And if it is possible would this code work when running Demo? What should I change/modify to get this to work?
You may want to modify your code something like this:
EDIT - This is a doubly-linked list implementation.
class Node {
int num;
Node prev;
Node next;
Node(int num) {
this.num = num;
}
Node(int num, Node prev, Node next) {
this.num = num;
this.prev = prev;
this.next = next;
}
void setPrev(Node prev) {
this.prev = prev;
}
void setNext(Node next) {
this.next = next;
}
}
class Lista {
Node root;
Node endNode;
public void add(int num) {
Node n = new Node(num);
if (root == null) {
root = n;
} else {
n.setPrev(endNode);
endNode.setNext(n);
}
endNode = n;
}
public void display() {
Node iterateeNode = root;
while (iterateeNode != null) {
System.out.print(iterateeNode.num + " ");
iterateeNode = iterateeNode.next;
}
}
}
The selected answer is technically not correct. For a (single) Linked List, all your Lista need is a single (head) node. Additionally, the Node class needs a single (next) Node field.
The following is a potential implementation of Node:
public class Node {
private Node next;
private int value;
public Node(int value) {
this.value = value;
}
public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void add(Node node) {
if (next == null) {
next = node;
} else {
Node temp = next;
while (temp != null) {
temp = temp.next;
}
temp = node;
}
}
#Override
public String toString() {
return String.valueOf(value);
}
}
The add() method will insert the new node in next if it is null. Otherwise, it will traverse the nodes until it finds the tail node (the one where next is null).
The Lista has only the first element in the list (head node).
public class Lista {
private Node head;
public void add(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.hasNext()) {
temp = temp.next();
}
temp.add(node);
}
}
// Other methods
}
When the add() function in the list is called, it will either add the new node as the head (if the list doesn't have one already) or rely on the already added nodes to figure out where the end of the list is in order to insert the new node.
Lastly, to display the list, just override the toString() method in node and add the "toString" value to a string buffer and send the concatenated string value to the console similar to the the code below.
public void display() {
StringBuilder buff = new StringBuilder("[");
buff.append(head);
if (head != null) {
Node next = head.next();
buff.append(",");
while (next != null) {
buff.append(next);
next = next.next();
buff.append(",");
}
}
buff.append("]");
int idx = buff.lastIndexOf(",");
buff.replace(idx, idx+1, "");
System.out.println(buff.toString());
}
Executing the following displays [3,9,7] as expected.
public class Demo {
public static void main ( String [] args) {
Lista lista = new Lista();
lista.add(new Node(3));
lista.add(new Node(9));
lista.add(new Node(7));
lista.display();
}
}
hello there i did the deep copy and the shallow copy is suggested by the user AndyMan and now i did the JUnit and im having a slight problem making those tests:
1.deep copy method
public ListNode<E> deep_clone() {
first = deep_clone(first);
ListNode<E> copy = new ListNode<>(first);
return copy;
}
private static Node deep_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(deep_clone(head.getNext()));
return temp;
}
Edit
many thanks for AndyMan for suggesting this shallow copy method:
private static Node shallow_clone(Node head) {
if (head == null)
return null;
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
but one question though how to Junit both the deep and shallow copy methods?
i did the following and i got a failed Junit test:
#Test
public void test_shallow_clone(){
ListNode<Integer> list =new ListNode<>();
for (int i = 0; i < 10; i++)
list.insert(i);
ListNode<Integer>cloned =list.shallow_clone();
//assertSame(cloned,list); //failed i dont know why
//assertEquals(cloned, list);//Even though its shallow copy i get that they are not equal!
assertSame(list.getFirst(), cloned.getFirst());
assertTrue(cloned.equals(list));
}
and the test for the deep copy:
#Test
public void test_depp_clone(){
ListNode<Integer> list =new ListNode<>();
for (int i = 0; i < 10; i++)
list.insert(i);
ListNode<Integer>cloned =list.depp_clone();
assertSame(cloned.getFirst(),list.getFirst());//check for same val..
//assertEquals(cloned, list);//this make the test fail..
assertFalse(cloned.equals(list));//okay the are not equal lists this means its deep copy...no implemented equal method :)
}
class ListNode
public class ListNode<E> implements Iterable<E>{
private Node<E> first;
//private Node<E> last;
public ListNode() {
first = null;
//last = null;
}
public ListNode(Node head) {
this.first = head;
//this.last = this.first;
}
public ListNode(E data) {
Node head = new Node(data);
this.first = head;
//this.last = this.first;
}
#Override
public Iterator<E> iterator() {
return new LL_Iterator<>(first);
}
private static class Node<E> {
private E data;
private Node next;
public Node() {
this.data = null;
this.next = null;
}
public Node(E data) {
this.data = data;
next = null;
}
public Node(E data, Node next) {
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E val) {
this.data = val;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
#Override
public String toString() {
return "Node{" + "data=" + data + ", next=" + next + '}';
}
}
private static class LL_Iterator<E> implements Iterator<E> {
private Node<E> curr;//we have to specify the E here because if we dont we have to cast the curr.getData()
public LL_Iterator(Node head) {
curr = head;
}
#Override
public boolean hasNext() {
return curr != null;
}
#Override
public E next() {
if (hasNext()) {
E data = curr.getData();
curr = curr.getNext();
return data;
}
return null;
}
}
public E getFirst(){
if(first==null)
return null;
return first.getData();
}
public boolean addFirst (E data) {
if(data==null)
return false;
Node t= new Node (data);
t.setNext(first);
first=t;
return true;
}
public E getLast() {
if (first==null)
return null;
return getLast(first).getData();
}
private static<E> Node<E> getLast(Node<E> head) {
if (head == null) {
return null;
}
Node temp = head;
if (temp.getNext() != null) {
temp = getLast(temp.getNext());
}
return temp;
}
//insertion....Wie setLast
public boolean insert(E data) {
if(data==null)
return false;
first = insert(first, data);
//last = getLast();
return true;
}
private static <E> Node insert(Node head, E data) {
if (head == null) {
return new Node(data);
} else {
head.setNext(insert(head.getNext(), data));
}
return head;
}
public void printList(){
LL_Iterator it= new LL_Iterator(first);
printUsingIterator(it,it.next());
}
private static<E> void printUsingIterator (LL_Iterator it, E data){
//VERDAMMT MAL RHEINFOLGE DER ANWEISUNGEN MACHT UNTERSCHIED
System.out.print(data+"->");
if (!it.hasNext()) {
System.out.print(it.next()+"\n");//THIS WILL PRINT NULL!!!
return;
}
printUsingIterator(it,it.next());
}
public int size() {
return size(first);
}
private static int size(Node head) {
if (head == null) {
return 0;
} else {
return 1 + size(head.getNext());
}
}
public boolean contains(E data) {
return contains(first, data);
}
public static <E> boolean contains(Node head, E data) {
if (head == null || data == null) {
return false;
}
if (head.getData().equals(data)) {
return true;
}
return contains(head.getNext(), data);
}
public int countIf(E t) {
return countIf(first, t);
}
private static <E> int countIf(Node head, E t) {
if (head == null ||t ==null) {
return 0;
}
if (head.getData().equals(t)) {
return 1 + countIf(head.getNext(), t);
}
return countIf(head.getNext(), t);
}
//TODO: WHY IM GETTING HERE AN OVERRIDE REQUEST FROM THE COMPILER??
//answer because im overriding the damn clone() of the list class which is shallow clone
public ListNode<E> depp_clone() {
first = depp_clone(first);
ListNode<E> copy = new ListNode<>(first);
return copy;
}
private static Node depp_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(depp_clone(head.getNext()));
return temp;
}
public ListNode shallow_clone (){
ListNode<E> cloned=new ListNode<>(shallow_clone(first));
return cloned;
}
private static Node shallow_clone(Node head) {
if (head == null)
return null;
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
Say head points to node0 which points to node1:
head = node0 => node1
In a deep copy, create two new nodes 7 and 8:
deepCopy = node7 => node6
In a shallow copy, create one new node 7 and copy reference to original node:
shallowCopy = node7 => node1
private static Node shallow_clone(Node head) {
if (head == null) {
return null;
}
Node temp = new Node(head.getData());
temp.setNext(head.getNext()); // Just copy the reference
return temp;
}
If the original node1 is changed, it will affect both the original and the shallow copy. it will not affect the deep copy.
Now for the terminology. What has been described is how to deep copy or shallow copy a node. It does not really make sense to shallow copy a linked list, because you are really just shallow coping a single node. Of course you can deep copy the list.
If it were an array, rather than a linked list, then you could shallow or deep copy.
To test these, override equals() and hashCode(). I would consider two lists equal if they have the same values. For two nodes to be equal, they should have the same value, and the rest of the list should be equal. If you don't override equals(), the implementation in Object is used. Object uses a bitwise comparison requiring the same references. You may want to look this up.
Also when overriding equals(), hashCode() needs to be overriden too. This is not directly related to the question, so you may want to look it after.
ListNode equals() and hashCode():
#Override
public boolean equals(Object otherObject) {
// Objects are equal if they have the same value, and next has the same value
if (otherObject instanceof ListNode) {
ListNode other = (ListNode)otherObject;
return first.equals(other.first);
}
else {
return false;
}
}
#Override
public int hashCode() {
return first.hashCode();
}
Node equals() and hashCode():
#Override
public boolean equals(Object otherObject) {
// Objects are equal if they have the same value, && next has the same value
if (otherObject instanceof Node) {
Node other = (Node)otherObject;
return data.equals(other.data) && ((next == null && ((Node) otherObject).getNext() == null) || next.equals(((Node) otherObject).next));
}
else {
return false;
}
}
#Override
public int hashCode() {
return data.hashCode();
}
public class Node<E> {
private E element;
public Node<E> next;
int data;
Node(int d)
{
data = d;
next = null;
}
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setElement(E element) {
this.element=element;
}
public void setNext(Node<E> n) {
next = n;
}
public void displayNode(){
System.out.print(element+ " ");
}
}
public class SinglyLinkedList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public SinglyLinkedList() {
head = tail = null;
size = 0;
}
public SinglyLinkedList(Node<E> head, Node<E> tail) {
this.head = head;
this.tail = tail;
}
public Node<E> getHead() {
return head;
}
public Node<E> getTail() {
return tail;
}
public void setHead(Node<E> head) {
this.head = head;
}
public void setTail(Node<E> tail) {
this.tail = tail;
}
public boolean isEmpty() {
if (head == null) {
return true;
}
return false;
}
public E first() {
return head.getElement();
}
public E last() {
return tail.getElement();
}
public void addFirst(E e) {
if (head == null) {
head = tail = new Node(e, null);
} else {
Node<E> newest = new Node(e, head);
head = newest;
}
size++;
}
public void addLast(E e) {
if (tail == null) {
head = tail = new Node(e, null);
} else {
Node<E> newest = new Node(e, null);
tail.setNext(newest);
tail = newest;
}
size++;
}
public E removeFirst() {
E e = head.getElement();
head = head.getNext();
size--;
return e;
}
#Override
public String toString() {
Node<E> tmp = head;
String s = "";
while (tmp != null) {
s += tmp.getElement();
tmp=tmp.getNext();
}
return s;
}
public void displayList() {
Node current = head;
while (current != null) {
current.displayNode();
current = current.next;
}
}
}
public interface Queue<E> {
int size();
boolean isEmpty();
void enqueue( );
E first();
E dequeue();
}
public class LinkedQueue<E> implements Queue<E> {
private SinglyLinkedList<E> list = new SinglyLinkedList<>();
public LinkedQueue() {
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void enqueue(E element) {
list.addLast(element);
}
public E first() {
return list.first();
}
public E dequeue() {
return list.removeFirst();
}
#Override
public void enqueue() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools |list.addLast(element);
}
public void displayQueue() {
list.displayList();
System.out.println();
}
public class Main {
public static void main(String[] args) {
LinkedQueue list = new LinkedQueue();
list.enqueue(sam);
list.enqueue(adams);
list.enqueue(john);
list.enqueue(isac);
list.enqueue(gad);
System.out.print("\n Linked list before calling swapNodes() ");
list.displayQueue();
}}
How to change the order of these names in the queue?
I have try to put function that swap nodes in the singlylinkedlist class but it didn't work.i m confused in which layer should i make this function in the linkedqueue class or the singlylinkedlist class or in the main class. yes i want just to swap names in the queue as simple as that.
UPDATED ANSWER
I modified your Node and NodeList Classes in a way which is easier to understand. I also kept similar private values and similar methods for those classes.
public class JavaApplication287 {
public static class Node{
private Node node;
private Node nextNode;
int data;
Node(int d){
data = d;
nextNode = null;
}
public Node getNode(){return node;}
public void setNode(Node someNode){node = someNode;}
public Node getNextNode(){return nextNode;}
public void setNextNode(Node someNextNode){nextNode = someNextNode;}
public int getData(){return data;}
public void setData(int d){data = d;}
public void printNode(){System.out.println(data);}
}
public static class NodeLinkedList{
private Node head;
private Node tail;
private int size;
NodeLinkedList(Node nodeHead, Node nodeTail, int s){
this.head = nodeHead;
this.tail = nodeTail;
this.size = s;
}
public Node getHead(){return head;}
public void setHead(Node n){head = n;}
public Node getTail(){return tail;}
public void setTail(Node n){tail = n;}
public int getSize(){return size;}
public void setSize(int n){size = n;}
public void printNodeList(){
System.out.println("Head: " + head.getData());
Node current = head;
while (current.nextNode != null){
System.out.println(current.data);
current = current.getNextNode();
}
System.out.println("Tail: " + tail.getData());
}
}
public static void main(String[] args) {
// create Sample Nodes
Node zero = new Node(0);
Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
//Link Them
zero.setNextNode(one);
one.setNextNode(two);
two.setNextNode(three);
three.setNextNode(four);
four.setNextNode(five);
//Create the Linked Node List with head = one & tail = five
NodeLinkedList myNodeLinkedList = new NodeLinkedList(zero, five, 6);
//Print Current LinkedNodes
myNodeLinkedList.printNodeList();
//Invert the NodeLinkedList
Node position = myNodeLinkedList.getHead(); //Node we look at
Node prev = null; // Store the prev Node
Node node = null; // Temp Node of the next Node in the Linked List
for (int i=0; i< myNodeLinkedList.getSize(); i++){
node = position.getNextNode(); //Store the Next Node so we do not lose access to it
position.setNextNode(prev); // Update current Node's NextNode value
prev = position; // Set previous Node as the Node we are currently looking at
position = node; // Move our position to the next Node
}
//Invert Head and Tail
Node temp = myNodeLinkedList.getHead();
myNodeLinkedList.setHead(myNodeLinkedList.getTail());
myNodeLinkedList.setTail(temp);
//Print Current LinkedNodes
myNodeLinkedList.printNodeList();
}
}
This is working code and here is the output I get,
run:
Head: 0
0
1
2
3
4
Tail: 5
Head: 5
5
4
3
2
1
Tail: 0
BUILD SUCCESSFUL (total time: 0 seconds)
Hope it helps,
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have scoured the internet and cannot find the answer to my question. I am currently in a data structures course, which is important to this question because I need to make EVERYTHING from scratch. I am currently working on homework and the question is this:
Using a USet, implement a Bag. A Bag is like a USet—it supports the add(x), remove(x), and find(x) methods—but it allows duplicate elements to be stored. The find(x) operation in a Bag returns some element (if any) that is equal to x. In addition, a Bag supports the findAll(x) operation that returns a list of all elements in the Bag that are equal to x.
I have done almost all of it and now when I am trying to test my code it throws a null pointer exception right off the bat. I went through the debugger and although I know where it is failing (when trying to create my array list and fill it with linked lists) I just dont know how to fix it. Here is what the error states:
Exception in thread "main" java.lang.NullPointerException
at Bag.<init>(Bag.java:10)
at Bag.main(Bag.java:198)
because I havent even gotten it to start I obviously dont know of any other errors it will encounter, but I will face those when this is fixed. I appreciate any help.
Reminder: I cannot use pre-built java dictionaries, everything needs to be done from the basics.
Here is my entire code:
public class Bag<T> {
final int ARR_SIZE = 128;
LinkedList[] theArray;
public Bag() {
for (int i = 0; i < ARR_SIZE; i++) {
theArray[i] = new LinkedList();
}
}
public boolean add(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
theArray[hashKey].addFirst(element, hashKey);
return true;
}
public T find(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].findNode(element).getData();
}
public T findAll(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
System.out.print(theArray[hashKey].findAllElements(element));
return element;
}
public T remove(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].removeElement(element);
}
public int size() {
return ARR_SIZE;
}
public class Node {
T data;
int key;
Node next;
Node prev;
public Node(T t, int k, Node p, Node n) {
data = t;
key = k;
prev = p;
next = n;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public void display() {
System.out.println(data);
}
}
public class LinkedList {
Node header;
Node trailer;
int size = 0;
public LinkedList() {
header = new Node(null, -1, trailer, null);
trailer = new Node(null, -1, null, null);
header.setNext(trailer);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public void addFirst(T t, int hashKey) {
Node currentLast = header.getNext();
Node newest = new Node(t, hashKey, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
}
public T add(T t) {
Node currentLast = header.getNext();
Node newest = new Node(t, -1, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
return newest.getData();
}
public T removeElement(T t) {
if (isEmpty()) {
return null;
}
T element = t;
return removeNode(findNode(element));
}
public T removeNode(Node node) {
if (isEmpty()) {
return null;
}
Node pred = node.getPrev();
Node succ = node.getNext();
pred.setNext(succ);
succ.setPrev(pred);
size--;
return node.getData();
}
public LinkedList findAllElements(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
LinkedList all = new LinkedList();
while (current != null) {
if (current.getData() == element) {
all.addFirst(element, -1);
} else {
current = current.getNext();
}
}
return all;
}
public Node findNode(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
while (current.getNext() != null && current.getData() != element) {
current = current.getNext();
}
if (current.getNext() == null && current.getData() != element) {
System.out.println("Does not exist");
}
return current;
}
}
public static void main(String[] args) {
Bag<Integer> bag = new Bag();
bag.add(1);
bag.add(1);
bag.add(2);
bag.add(2);
bag.add(8);
bag.add(5);
bag.add(90);
bag.add(43);
bag.add(43);
bag.add(77);
bag.add(100);
bag.add(88);
bag.add(555);
bag.add(345);
bag.add(555);
bag.add(999);
bag.find(1);
}
}
Initialize your theArray to avoid NullPointerExceptions.
LinkedList[] theArray = new LinkedList[ARR_SIZE];
I have been diligently watching YouTube videos in an effort to understand linked lists before my fall classes start and I am uncertain how to proceed with iterating over the following linked list. The 'node' class is from a series of videos (same author), but the 'main' method was written by me. Am I approaching the design of a linked list in an illogical fashion (assuming of course one does not wish to use the predefined LinkedList class since the professor will expect each of us to write our own implementation)?:
class Node
{
private String data;
private Node next;
public Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}
public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}
public static int size(Node list)
{
int count = 0;
while (list != null)
{
count++;
list = list.getNext();
}
return count;
}
}
public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);
}
}
Thanks for the help,
Caitlin
There are some flaws in your linked list as stated by some of the other comments. But you got a good start there that grasps the idea of a linked list and looks functional. To answer your base question of how to loop over this particular implemention of the linked list you do this
Node currentNode = n1; // start at your first node
while(currentNode != null) {
// do logic, for now lets print the value of the node
System.out.println(currentNode.getData());
// proceed to get the next node in the chain and continue on our loop
currentNode = currentNode.getNext();
}
Maybe this will be useful:
static void iterate(Node head) {
Node current = head;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
// or through recursion
static void iterateRecursive(Node head) {
if (head != null) {
System.out.println(head.getData());
iterateRecursive(head.getNext());
}
}
class List {
Item head;
class Item {
String value; Item next;
Item ( String s ) { value = s; next = head; head = this; }
}
void print () {
for( Item cursor = head; cursor != null; cursor = cursor.next )
System.out.println ( cursor.value );
}
List () {
Item one = new Item ( "one" );
Item two = new Item ( "three" );
Item three = new Item ( "Two" );
Item four = new Item ( "four" );
}
}
public class HomeWork {
public static void main( String[] none ) { new List().print(); }
}
Good luck!!
You can have your linked list DS class implement 'Iterable' interface and override hasNext(), next() methods or create an inner class to do it for you. Take a look at below implementation:
public class SinglyLinkedList<T>{
private Node<T> head;
public SinglyLinkedList(){
head = null;
}
public void addFirst(T item){
head = new Node<T>(item, head);
}
public void addLast(T item){
if(head == null){
addFirst(item);
}
else{
Node<T> temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node<T>(item, null);
}
}
private static class Node<T>{
private T data;
private Node<T> next;
public Node(T data, Node<T> next){
this.data = data;
this.next = next;
}
}
private class LinkedListIterator implements Iterator<T>{
private Node<T> nextNode;
public LinkedListIterator(){
nextNode = head;
}
#Override
public boolean hasNext() {
return (nextNode.next != null);
}
#Override
public T next() {
if(!hasNext()) throw new NoSuchElementException();
T result = nextNode.data;
nextNode = nextNode.next;
return result;
}
}
}