Acces Linked Lists Nodes directly from main - java

I have a List
public class SinglyLinkedList {
//---------------- nested Node class ----------------
private static class Node {
private String element; // reference to the element stored at this node
private Node next; // reference to the subsequent node in the list
public Node(String e, Node n) {
element = e;
next = n;}
public String getElement( ) { return element; }
public Node getNext( ) { return next; }
public void setNext(Node n) { next = n; }
}
// instance variables of the SinglyLinkedList
private Node head = null; // head node of the list (or null if empty)
private Node tail = null; // last node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList( ) { } // constructs an initially empty list
// access methods
public int size( ) { return size; }
public boolean isEmpty( ) { return size == 0; }
public String first( ) {
// returns (but does not remove) the first element
if (isEmpty( )) return null;
return head.getElement( );
}
public String last( ) {
// returns (but does not remove) the last element
if (isEmpty( )) return null;
return tail.getElement( );
}
// update methods
public void addFirst(String e) {
// adds element e to the front of the list
head = new Node(e, head); // create and link a new node
if (size == 0)
tail = head; // special case: new node becomes tail also
size++;
}
public void addLast(String e) {
// adds element e to the end of the list
Node newest = new Node(e, null); // node will eventually be the tail
if (isEmpty( ))
head = newest; // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
}
My main looks like:
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
SinglyLinkedList Liste1 = new SinglyLinkedList();
//Bam funktioniert
Liste1.addFirst("Hello world!");
}
}
I would like to add Cursors in the main something like:
Cursor C1 = new addCursor(3);
This C1 Cursor point to list element nr. 3
Cursor C2 = new addCursor(5);
This C2 Cursor points to list element nr.5 ( if exists)
I would like to use cursors in main. So the function addCursor would be in the SinglyLinkedList class but it would return Cursors to Nodes.
So Curser would be like a crab sitting on the node.
Is it possible?
If not maybe other suggestion?

First you can create the Cursor class:
public class Cursor {
private SinglyLinkedList.Node cursor;
Cursor(SinglyLinkedList.Node cursor){
this.cursor = cursor;
}
public SinglyLinkedList.Node getCursor(){
return cursor;
}
}
then the method addCursor in the SinglyLinkedList class:
Cursor addCursor(int value){
int count = 0;
Node tmp = head;
while(tmp != null){
count++;
if(count == value)
return new Cursor(head);
tmp = tmp.next;
}
return null;
}
this method will search in the linked list and return the element in the position equals to value.
Then calling from the main:
public static void main(String[] args) {
System.out.println("Hello world!");
SinglyLinkedList Liste1 = new SinglyLinkedList();
//Bam funktioniert
Liste1.addFirst("Hello world!");
Cursor C1 = Liste1.addCursor(3);
.....
}

Related

How to modify the head of a LinkedList without a wrapper class?

When I create a Node object and call "appendToTail" the Node object has a sequence of nodes via the next attribute (as expected). I tried creating a pop, where it takes the head (aka 'this') and reference it with a variable and overwrite it with its next. However, 'this' remains the same as the original head. What am I doing wrong, or is there no way to modify 'this'?
public class Node {
Node next = null;
int data;
public Node(int d) {
data = d;
}
public void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
public void popHead() {
Node n = this;
n = n.next;
}
}
Basically you need to construct a custom List and add each node at End. Also you need to store first node in order to have the starting point for looping.
public class NodeList
{
Node head=null;
public static void main(String args[])
{
NodeList nl = new NodeList();
nl.addNode(1);
nl.addNode(2);
nl.addNode(3);
nl.listNodes();
}
public void addNode(int data)
{
if(head==null)
{
head = new Node(data);
}
else
{
Node curent = head;
while(curent.next != null)
{
curent = curent.next;
}
curent.next = new Node(data);
}
}
public void listNodes()
{
if(head !=null)
{
Node curent = head;
System.out.println(curent.data);
while(curent.next !=null)
{
curent = curent.next;
System.out.println(curent.data);
}
}
}
class Node
{
Node next = null;
int data;
public Node(int d) {
data = d;
}
}
}
Output
1
2
3

Parsing Through ListNodes in List

I'm having trouble figuring out why my code won't parse through the ListNodes in the Lists, in order to add a new String as a ListNode. I'm trying to write the function add(String s), to add a new ListNode to the List. If the list is empty, I just add the String as a ListNode, and if not, I parse through using node and myNext, and then if node.myNext is null, I replace it with the newly created ListNode. What is the reason this isn't working? It either does not throw an output or it says it is out of bounds.
public class List {
private ListNode myHead;
private int mySize;
public List() {
this.myHead = null;
this.mySize = 0;
}
public class ListNode {
public String myData;
public ListNode myNext;
public ListNode(String element, ListNode next) {
this.myData = element;
this.myNext = next;
}
public ListNode(String element) {
this(element, null);
}
public boolean isEmpty() {
return this.length() == 0;
}
public void add(String s) {
if(this.isEmpty() == true) {
this.addToFront(s);
}
else {
this.mySize++;
for(ListNode node = this.myHead; node.myData != null; node = node.myNext) {
if(node.myNext == null) {
ListNode lno = new ListNode(s, null);
node.myNext = lno;
}
else {
node.myData = node.myData;
}
}
}
}
In you ListNode you can't access methods and variables of your List class.
Assuming that you want to add the new String at the top of your List you should do something like this:
public class List {
private ListNode myHead;
private int mySize;
public List() {
this.myHead = null;
this.mySize = 0;
}
public boolean isEmpty() {
return this.mySize == 0;
}
public void add(String s) {
this.myHead = new ListNode(s, myHead);//add new String as head element
this.mySize++;
}
}
public class ListNode {
public String myData;
public ListNode myNext;
public ListNode(String element, ListNode next) {
this.myData = element;
this.myNext = next;
}
public ListNode(String element) {
this(element, null);
}
}
If you want to add it at the end of your List you can try it like this:
public void add(String s) {
if(this.isEmpty()){
this.myHead = new ListNode(s, myHead);//add new String as head element
}else{
ListNode node = this.myHead;
while (node.myNext != null){
node = node.myNext;
}
//now you hav the last node of your list
node.myNext = new ListNode(s,null);
}
this.mySize++;
}
The code you have pasted is not complete.
Also, If I am correct, your List is having the ListNodes and thus, it is your List where you should put methods to check if it is Empty (does not have any ListNodes in it) or add, delete, count, search etc. functions.
For isEmpty(), There is no length() defined, so simply check the size to be == 0.
For add(), if it is empty just point myHead to your new ListNode; If you have to add in end, iterate the myHead using a currentNode reference, till its next is null and add.
If it is to be in middle somewhere, you will need to check for ListNode myData to decide where it fits white moving from myHead towards null and once you find a place to insert, you will need to change the [PrevNode] -> new ListNode -> [nextNode]

add method not working for linked list in Java

I'm trying to create a method that will add a node to my linked list. The method takes a String. This is the method that I created:
public void add(String x)
{
Node newNode = new Node();
newNode.element = x;
newNode.nextNode = firstNode;
firstNode = newNode;
}
Unfortunately, this code isn't working. Is there a way I can alter it to make it work?
Here are all the information I was provided with:
Linked List Class with Node inner-class:
class LinkedList implements StringCollection
{
private static class Node
{
public String element;
public Node nextNode;
public Node (String element)
{
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
public NodeStringCollection ()
{
firstNode = null;
}
//add method goes here
public String toString ()
{
String s = "";
Node node = firstNode;
while (node != null)
{
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
Tested Linked Class:
Class Test
{
public static void main(String [] args)
{
StringCollection sc = new LinkedList ();
sc.add (new String ("A"));
sc.add (new String ("B"));
sc.add (new String ("C"));
sc.add (new String ("D"));
System.out.println (sc);
int countStrings = sc.size ();
System.out.println (countStrings);
}
}
The Output
D C B A
4
I fixed your code. What you did wrong is that the element that you added to the LinkedList replaced the old firstNode. So the last node that you add to your implementation would become the new first node. Therefore, your LinkedList printed D C B A which is the reverse of what it should be.
The code below stores the first node and the last node. When a new node is added, we let the last node point to the newly created node and then set the last node to the newly created node:
Code
public class LinkedList {
public static class Node {
public String element;
public Node nextNode;
public Node(String element) {
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
private Node lastNode;
public LinkedList() {
firstNode = null;
lastNode = null;
}
public void add(String x) {
Node newNode = new Node(x);
if (firstNode == null)
firstNode = newNode;
if (lastNode != null)
lastNode.nextNode = newNode;
lastNode = newNode;
}
public String toString() {
String s = "";
Node node = firstNode;
while (node != null) {
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
Example code
public static void main(String args[]) throws Exception {
LinkedList sc = new LinkedList();
sc.add(new String("A"));
sc.add(new String("B"));
sc.add(new String("C"));
sc.add(new String("D"));
System.out.println(sc);
}
Output
A B C D

DoublyLinkedList getting data from node

I have created a Doubly Linked List, and I am trying to call the getData method from the Linked List. However it is not working. I am trying to get this from the node. Here is the code from the Node.
private class Node<AnyType>
{
AnyType data;
Node<AnyType> next;
Node<AnyType> previous;
//Creates the Node with the parameters of data next and previous
public Node(AnyType data,Node<AnyType> next, Node<AnyType> previous )
{
this.data = data;
this.next = next;
this.previous = previous;
}
//Getters and setters for data next and previous
public AnyType getData() {
return data;
}
public Node<AnyType> getNext() {
return next;
}
public Node<AnyType> getPrevious() {
return previous;
}
public void setData(AnyType data) {
this.data = data;
}
public void setNext(Node<AnyType> next) {
this.next = next;
}
public void setPrevious(Node<AnyType> previous) {
this.previous = previous;
}
}
It may be a problem that it says that setData(AnyType data), is never used locally, however im not sure on that.
Now to where im trying to use the getData method. This is in an animate method,
if (USE_LINKED_LIST)
{
for (int i = 0; i < this.linked_list.size(); i++)
{
Movable current = this.linked_list.getData();
current.move(frame_rate_duration);
if(current.dead())
{
this.linked_list.remove(current);
i--;
}
}
}
The this.linked_list.getData() is giving me the error saying I must create method getData() in DoublyLinkedList. Im sure this is just a simple error but anything helps! thanks!
Here is the entire LinkedList class
package Our_Fireworks;
/**
*
* #author Ben Hammond
*
* #param <AnyType>
*/
public class DoublyLinkedList <AnyType>
{
private Node<AnyType> header;
private Node<AnyType> footer;
public DoublyLinkedList()
{
//Creates the header Node with data set to null, next set to footer, previous set to null
header = new Node<AnyType>(null, footer, null);
footer = new Node<AnyType>(null, null, header);
}
// Creates the insert method used to insert a Node into the linked list
public void insert(AnyType data)
{
//Creates a new node to insert before the footer
Node<AnyType> newNode = new Node<AnyType>(data, footer, footer.previous);
//Sets the node previous to footer, to link to the new Node
footer.previous.setNext(newNode);
//Sets the footer node to be linked to the new Node
footer.setPrevious(newNode);
}
//Remove method to remove a Node from the linked list
public void remove (AnyType data)
{
//Starts the iteratorLooper from the first Node in the list
Iterator<AnyType> iteratorLooper = first();
//Runs the while loop as long as valid = true
while(iteratorLooper.valid())
{
//Once you receive the correct data, the loop will stop
if(iteratorLooper.getData().equals(data))
{
break;
}
//Goes to the next data member
iteratorLooper.next();
}
//Once the while loop breaks, it will delete that data member
iteratorLooper.remove();
}
//Creates the size method
public int size()
{
//Creates an int variable
int count = 0;
//Starts the iteratorLooper at the first Node
Iterator<AnyType> iteratorLooper = first();
//As long as valid returns true the while loop will run
while(iteratorLooper.valid())
{
//Will add to the count variable
count++;
//Goes to the next Node
iteratorLooper.next();
}
//Returns the count once the while loop is complete
return count;
}
//Creates the first method
public Iterator<AnyType> first()
{
//Creates a new Iterator, at header.next
Iterator<AnyType> newIterator = new Iterator<AnyType>(header.next);
//Returns the Iterator
return newIterator;
}
//Creates the last method
public Iterator<AnyType> last()
{
//Creates a new Iterator at footer.previous
Iterator<AnyType> newIterator = new Iterator<AnyType>(footer.previous);
//Returns the Iterator
return newIterator;
}
//Iterator find method
public Iterator<AnyType> find(AnyType data)
{
Iterator<AnyType> iteratorLooper = first();
//As long as valid returns true the while loop runs
while(iteratorLooper.valid())
{
//runs the loop until data is equal to "getData"
if(iteratorLooper.getData().equals(data))
{
break;
}
iteratorLooper.next();
}
//Returns iteratorLooper
return iteratorLooper;
}
//Creates the Node class
private class Node<AnyType>
{
AnyType data;
Node<AnyType> next;
Node<AnyType> previous;
//Creates the Node with the parameters of data next and previous
public Node(AnyType data,Node<AnyType> next, Node<AnyType> previous )
{
this.data = data;
this.next = next;
this.previous = previous;
}
//Getters and setters for data next and previous
public AnyType getData() {
return data;
}
public Node<AnyType> getNext() {
return next;
}
public Node<AnyType> getPrevious() {
return previous;
}
public void setData(AnyType data) {
this.data = data;
}
public void setNext(Node<AnyType> next) {
this.next = next;
}
public void setPrevious(Node<AnyType> previous) {
this.previous = previous;
}
}
//Creates the Iterator class
public class Iterator<AnyType>
{
//Creates a new node of currentNode
private Node<AnyType> currentNode;
public Iterator(Node<AnyType> currentNode)
{
this.currentNode = currentNode;
}
//Creates the valid method
public boolean valid()
{
//Checks to see if current node is not equal to the header footer, or null
if (currentNode != header && currentNode != footer && currentNode != null)
{
//If the statement is true it returns true
return true;
}
else
{
//If it is not true... it simply returns false
return false;
}
}
//Creates the next method
public void next()
{
//Checks if the next Node is not equal to null
if(currentNode.getNext() != null)
{
//Gets the next node, of what ever the current node is
currentNode = currentNode.getNext();
}
}
//Creates the previous method
public void previous()
{
//Checks if the previous Node is not equal to null
if(currentNode.getPrevious() != null)
{
//Gets the previous node of currentNode
currentNode = currentNode.getPrevious();
}
}
public AnyType getData()
{
//Gets the data inside the currentNode
return currentNode.getData();
}
//Creates the remove method
public void remove()
{
//As long as valid returns true than the if statement will run
if(valid())
{
currentNode.getPrevious().setNext(currentNode.getNext());
currentNode.getNext().setPrevious(currentNode.getPrevious());
currentNode = currentNode.getPrevious();
}
}
//Creates the insert method with the parameters of AnyType and data
public void insert(AnyType data)
{
//Creates a newNode to be inserted after currentNode
Node<AnyType> newNode = new Node<AnyType>(data, currentNode.next, currentNode );
currentNode.getNext().setPrevious(newNode);
currentNode.setNext(newNode);
}
}
}
You have getData() method for Node, not for your linked list class. I think you meant something like
Movable current = this.linked_list.get(i).getData();
(Provided your linked list class has a getter for index)
Usually linked lists don't have random access getters, so most likely the whole code should be written differently:
for (Node<Movable> node = linked_list.getHead(); node != null; node = node.getNext()) {
Movable current = node.getData();
...
}
EDIT: So you have getData() in your Iterator:
for (Iterator<Movable> iter = linked_list.first(); iter.valid(); iter.next()) {
Movable current = iter.getData();
...
}

How do I write basic Doubly Linked List functions in Java?

My first assignment in my programming class is about writing code for a Doubly Linked List, which includes writing an add, remove, size, iterator first, iterator last, and iterator find functions. I have spent 3 hours and gotten no where in understanding this. I understand what happens if I can see it in a picture. But my problem is translating it to code. This is what I have so far:
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data, node next, node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null, null, null);
footer = new node(null, header, null);
header.next = footer;
}
public void add(G data) {
header.next = new node(data, footer.prev, footer);
}
public int size() {
node current = header.next;
int quanity = 0;
if (current == null) {
return 0;
}
while (current != null) {
current = current.next;
quanity++;
}
return quanity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
As you can see, I've been using the main() to test everything. From what I've been told by my teacher, my constructor and node class look fine. However I know either my add and size are not right because when I test this, when there is no nodes in the list, it displays nothing, but it should display 0 right? I mean, assuming my size code is right, which I'm not sure of.
And whenever I add a node, no matter how many I add, it always displays 1. So either both add and size are broken, or both are. I have not written the other functions as it makes no sense until I figure these ones out. Please someone help me understand this! Thank you.
Declare a size field in DoublyLinkedList to store the current size of the list. When add succeed, make size++. When remove succeed, make size--. And size() method just simply return the value of size.
The sample code is here:
private int size = 0;
public void add(G data) {
header.next = new node(data, footer.prev, footer);
size++;
}
public int size() {
return size;
}
Noticed couple of things:
First, footer is not constructed correctly. It should be:
public DoublyLinkedList() {
..
footer = new node(null, null, header);
// your code is incorrectly creating a circular list
..
}
Secondly add() method doesn't look correct. It should be something like :
public void add(G data) {
Node newNode = new Node(data, header, null);
header.prev = newNode
header = newNode;
}
// for adding at the front (LIFO)
OR
public void add(G data) {
Node newNode = new Node(data, null, footer);
footer.next = newNode
footer = newNode;
}
//for adding at the tail (FIFO)
Check out the wikipedia entry for doubly linked lists. It has some good pseudo code.
Using your own code I'm going to make a few suggestions
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null);
footer = new node(null);
header.next = footer;//link the header to the footer
footer.prev = header;//link the footer to the header
}
public void add(G data) { //assuming you are adding the node to the head of the list
node newNode = new node(data); //creating new node to add with the data
newNode.next = header.next; // setting new node to head of the list or the footer
newNode.prev = header; //setting the new node's previous node to the header
header.next = newNode; //setting the newNode as the next node.
}
public int size() {
node current = header.next;
int quantity = 0;
if (current.data == null/*Empty list*/) { //you needed to specify what you were trying to test
return 0;
}
while (current.data != null/*traversing the list*/) {
current = current.next;
quantity++;
}
return quantity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
Here you go:
public class DoublyLinkedList {
private class Node {
String value;
Node next,prev;
public Node(String val, Node n, Node p) {
value = val;
next = n;
prev=p;
}
Node(String val) {
this(val, null, null);
}
}
private Node first;
private Node last;
public DoublyLinkedList() {
first = null;
last = null;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
int count=0;
Node p=first;
while(p!=null){
count++;
p=p.next;
}
return count;
}
public void add(String e) {
if(isEmpty()){
last=new Node(e);
first=last;
}
else{
last.next=new Node(e, null, last);
last=last.next;
}
}
public void add(int index, String e){
if(index<0||index>size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if(index==0){
Node p=first;
first=new Node(e,p,null);
if(p!=null)
p.prev=first;
if(last==null)
last=first;
return;
}
Node pred=first;
for(int k=1; k<=index-1;k++){
pred=pred.next;
}
Node succ=pred.next;
Node middle=new Node(e,succ,pred);
pred.next=middle;
if(succ==null)
last=middle;
else
succ.prev=middle;
}
public String toString(){
StringBuilder strBuilder=new StringBuilder();
Node p=first;
while(p!=null){
strBuilder.append(p.value+"\n");
p=p.next;
}
return strBuilder.toString();
}
public String remove(int index){
if(index<0||index>=size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
Node target=first;
for(int k=1; k<=index;k++){
target=target.next;
}
String element=target.value;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return element;
}
public boolean remove(String element){
if(isEmpty())
return false;
Node target=first;
while(target!=null&&!element.equals(target.value))
target=target.next;
if(target==null)
return false;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return true;
}
public static void main(String[] args){
DoublyLinkedList list1=new DoublyLinkedList();
String[] array={"a","c","e","f"};
for(int i=0; i<array.length; i++){
list1.add(array[i]);
}
list1.add(1,"b");
list1.add(3,"d");
System.out.println(list1);
}
}

Categories