add() method for a linked list - java

I'm trying to create a method that will add a node to a linked list but so far have been unsuccessful. Here's my code with my member vars:
private Object data;
private int size = 0;
private Node head = null;
private Node tail = null;
public void add(Object item){
Node temp = head;
if (head != null) {
// THIS IS THE PROBLEM SITE
while(temp.getNext()!=null){
temp=temp.getNext();
}
//set next value equal to item
Node ab = (Node) item; // It says this is an invalid cast. How do I get around this??
ab.setNext(ab);
}
else{
head = new Node(item);
}
size++;
}
Also here's my Node class for reference:
public class Node {
// Member variables.
private Object data; // May be any type you'd like.
private Node next;
public Node(Object obj) {
this.data = obj; // Record my data!
this.next = null; // Set next neighbour to be null.
}
// Sets the next neighbouring node equal to nextNode
public void setNext(Node nextNode){
this.next=nextNode;
}
// Sets the item equal to the parameter specified.
public void setItem(Object newItem){
this.data = newItem;
}
// Returns a reference to the next node.
public Node getNext(){
return this.next;
}
// Returns this node ís item.
public Object getItem() {
return this.data;
}
Thanks for your time!

you don't want to cast your item as a node, you want to create a new node and set the data in it to be the item
replace this :
Node ab = (Node) item; // It says this is an invalid cast. How do I get around this??
ab.setNext(ab);
by something like this :
Node newNode = new Node();
newNode.setData(item);
temp.setNext(newNode);

Related

Recursively adding a new node to the end of a LinkedList?

Having a lot of trouble trying to write a recursive method to add a new Node to the end of a LinkedList. I've been staring at this for a looooong time and still my terminal is printing blanks...if someone can help me out that would be greatly appreciated! Still trying to wrap my head around the concept of recursion. If I try to do the problem iteratively with a while loop, then I'm able to do it no problem but my assignment requires me to write it recursively. Thanks for the help :)
public class LinkedList
{
//
//Instance variable
//
private Node top;
//
//Instance and static methods below
//
//Accessor for the top Node
public Node getTop()
{
return top;
}
public void add(Object data) {
Node newNode = new Node(data,null);
addRec(top,newNode);
}
private Node addRec(Node start, Node newNode) {
if (start == null) {
start = newNode;
return start;
}
start.setLink(addRec(start.getLink(), newNode));
return start;
}
public String toString() {
String value = "";
Node current = top;
while (current != null) {
value += current.getData();
current = current.getLink();
}
return value;
}
Node class:
public class Node
{
//
//Instance variables
//
private Object data;
private Node link;
//
//Constructor
//
public Node (Object initData, Node initLink)
{
data = initData;
link = initLink;
}
//
//Accessors
//
public Object getData()
{
return data;
}
public Node getLink()
{
return link;
}
public void setData(Object data) {
this.data = data;
}
//
//Mutators
//
public void setLink(Node newLink)
{
link = newLink;
}
}
Recursively adding a node to the linked list is a fairly straightforward concept.
Lets look at the algorithm:
1] If the given node does not have a node after it (which we will call the next node), we add the current node.
2] Otherwise, we add the node to the next node. This would involve performing step 1 on the next node.
If you notice, Step 2 has a recursive call to step 1, as it is referencing the same node.
To implement this, first, we create a child class called Node, inside the LinkedList. This will require an int to store the data, and a Node that points to the next Node.
we create the method add() inside Node.
To implement step 1, we check if next is equal to null. If it is, we add the node as the next on on the linked list.
if(this.next== null)this.next= toAdd;
To implement step 2, we say otherwise, we call the method add on the next Node, and pass the value to add.
if(this.next== null)this.next= toAdd;
Now, we have to implement this in the class LinkedList.
We declare a root node, where the list starts.
Now, we declare a method that will do the following:
add a value to root.
That's it.
Recursion takes care of the rest.
Think about it, if root has a node after it, the data will be added to the next node, and so on.
Therefore, problem sorted, you have your list!
public class LinkedList
{
private Node root;
private class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
public void add(Node toAdd){
if(this.next== null)this.next= toAdd;
else this.next.add(toAdd);
}
}
public LinkedList(int root){
this.root = new Node(root);
}
public void add(int toAdd){
this.root.add(new Node(toAdd));
}
}

How can i set a TREE NODE<T> with two informations-[STRING.INT]?

I am writing a program where i have to create a Double linked list full of nodes which user can insert with own values.I have methods to insert the new node into different parts of the list(front, in position,tail). Each node has two informations, one String and the oder INT (both are set by user after creating a new node.
My problem here is how can i set the first information as String, (in the exaple i give there is the version with bot elements INT, but the first one must be string and this is where i need help)
public void insertInFirstPosition(int information,int key) {
Node n = new Node(information,key, null, null);
if (head == null) {
n.setLinkNext(n);
n.setLinkPrev(n);
head = n;
tail = head;
} else {
n.setLinkPrev(tail);
tail.setLinkNext(n);
head.setLinkPrev(n);
n.setLinkNext(head);
head = n;
}
size++;
}
HERE IS THE NODE CLASS `
public class Node {
private int data;
private int informazione;
private Node next, prev;
/* Constructor */
public Node() {
next = null;
prev = null;
data = 0;
informazione = 0;
}
public Node(int i,int k, Node n, Node p) {
data = i;
informazione = k;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext (Node n) {
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p) {
prev = p;
}
/* Funtion to get link to next node */
public Node getNext() {
return next;
}
/* Function to get link to previous node */
public Node getPrev() {
return prev;
}
/* Function to set information to node */
public void setInformazione(int i) {
informazione = i;
}
/* Function to get data from node */
public int getInformazione() {
return informazione;
}
/* Function to set data to node */
public void setData(int d) {
data = d;
}
/* Function to get data from node */
public int getData() {
return data;
}
}`
in this code you can only enter INT values for both of the node slots, the second slot is fine, must be an int, meanwhile the first slot have to be an String.
Thank all for help.
You should make your Node class generic, and let it accept any class as data.
class Node<T> {
T data;
Node<T> prev;
Node<T> next;
public Node (T data, Node<T> prev, Node<T> next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
Now you can define a class (let's call it SomeClass) that contains all the properties you want to store in a given Node, and create a Node with:
Node<SomeClass> n = new Node<SomeClass>(new SomeClass(information,key), null, null);

Keeping the dummy nodes in linked list

I'd like to add new nodes into the list without removing/substituting the dummy node head, i.e. head is always null and the list would start from head.next (head -> node -> node -> node). I'm having trouble with the syntax of the dummy node and Im not sure if Im doing it right at all. Could smb please take a look? Thanks in advance!
Im getting a nullPointer in this line of the constructor:
this.head.next = null;
CODE
package SinglyLinkedList;
import java.util.*;
public class Tester {
public static void main(String[] args){
LinkedList<Integer> myList = new LinkedList<Integer>();
myList.insert(1);
myList.insert(2);
myList.insert(3);
myList.displayList();
}
}
Class Link
package SinglyLinkedList;
import java.util.Iterator;
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data){
this.data = data;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
this.head = null;
this.head.next = null;
this.size = 0;
}
public boolean isEmpty(){
return head == null;
}
public void displayList(){
if(head.next == null){
System.out.println("The list is empty");
}
else{
Node<T> current = head.next;
while(current != null){
current.display();
current = current.next;
}
}
}
public void insert(T data){
Node<T> newNode = new Node<T>(data);
if(head.next == null){
head.next = newNode;
}
else{
newNode.next = head.next;
head.next = newNode;
}
size++;
}
#Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return null;
}
}
I guess you have misunderstood the concept of linked lists. The member variable head points to the start address of the linked list. It cannot be null. head.next should point to the second element while head itself points to the first element. Moreover, you don't have to change the value of head while adding new nodes to the list unless the node you insert is supposed to be placed at the beginning of the linked list. In that case, you need to update head to point to the new node. For inserting nodes in the middle or at the end of the linked list, this is not required.
Further reading:
http://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
http://www.tutorialspoint.com/java/java_linkedlist_class.htm

Initializing linked list with elements in a treeSet

The question is this:
Define a constructor that takes a TreeSet as a parameter and initializes a linked list with the elements in the set. The new list must be sorted in increasing lexicographic order.
This method is to be implemented using the class below:
public class LinkedList<T extends Comparable<T>> {
private class Node{
private T data;
private Node next;
private Node(T data){
this.data = data;
next = null;
}
}
private Node head;
public LinkedList(){
head = null;
}
Now I know a TreeSet is inherently sorted so all I'd really have to do here is take the element from the TreeSet and put it to the front of this linked list. But I'm having trouble retrieving the element from the set and adding it to the LinkedList. I wrote a private helper add(T data) method and am using it but I don't know if this is how I should approach it. I'm new to data structures so have little idea about sets and their implementations.
public class LinkedList<T extends Comparable<T>> {
private class Node{
private T data;
private Node next;
private Node(T data){
this.data = data;
next = null;
}
}
private Node head;
public LinkedList(){
head = null;
}
public void add(T data){
Node n = new Node(data);
if(head == null){
head = n;
}
else{
n.next = head;
head = n;
}
}
public LinkedList(TreeSet<T> test){
Iterator<T> itr = test.iterator();
while(itr.hasNext()){
this.add(itr.next());
}
}
The main problem you have to solve is that you need to add each item to the end of the list not the start.
Adding a node to the start of the list is easy:
public void addToHead(T data) {
Node node = new Node(data);
node.next = head;
head = node;
}
Adding to the end is harder because you don't have a reference to the tail. But the solution is fairly simple: in the constructor you are developing, keep a reference to the tail of the list so that you can add each value at the end of the links rather than the start.
The question includes "increasing lexicographic order."
My solution is without helper method:
public LinkedList(TreeSet<T> test){
Node currNode = null;
for(T data : test) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
currNode = head;
}
else {
currNode.next = newNode;
currNode = currNode.next;
}
}
}

removing from a linked list

I made an SListClass which stands for sinle-linked list class and a node class SListNode. I'm having a problem with the removeLast method. When I print out the list of nodes, the first item is still there. I don't understand why
public class SListClass {
private SListNode head;
private double size;
SListClass(){
head = null;
size = 0;
}
SListClass(SListNode node){
head = node;
}
public void insertFront(int item){
head = new SListNode(item, head);
size++;
}
public void addLast(SListNode head, int value){
SListNode first = head;
while(first.next != null){
first = first.next;
}
first.next = new SListNode(value, null);
size++;
}
public void removeFirst(SListNode head){
head = head.next;
}
/*public String toString(){
return String.format(head + "");
}
*/
public String print(){
String result = head.item + " ";
if(head.next != null){
result += head.next.print();
}
return result;
}
public static void main(String[] args) {
SListNode list = new SListNode(21, new SListNode(5, new SListNode(19, null)));
SListClass x = new SListClass(list);
x.insertFront(33);
x.insertFront(100);
x.addLast(list, 123);
x.addLast(list, 9999);
x.removeFirst(list);
System.out.println(x.print());
}
}
output: 100 33 21 5 19 123 9999
The SListNode class:
public class SListNode {
protected int item;
protected SListNode next;
public SListNode(int item, SListNode next){
this.item = item;
this.next = next;
}
public SListNode(int item){
this(item, null);
}
public int getItem() {
return item;
}
public void setItem(int item) {
this.item = item;
}
public SListNode getNext() {
return next;
}
public void setNext(SListNode next) {
this.next = next;
}
}
Change the removeFirst to this.head = head.next. The head in the parameter list is hiding the class field head.
Also, consider this: in a removeFirst method, do you really want a head parameter, or should you use the head field instead since that is the real head for the linked list you are trying to update? If you don't want that parameter anymore, just delete the parameter from the method signature; then the field head is not hidden, so head = head.next does fine.
First of all, your naming is bad. Every class is a class, so ending the name of a class with Class is just noise. On the contrary S doesn't mean anything. If you must explain what SListClass stands for, then it means that the name is bad, and that you should choose another name, which doesn't need any explanation, like SinglyLinkedList.
The users of your class shouldn't care how the list retains the information. It should never have to pass a Node to any method. Only a value. So the following methods should be modified:
SListClass(SListNode node) --> SinglyLinkedList(int value)
void addLast(SListNode head, int value) --> void addLast(int value) : the list knows what the head node is. It makes no sense to pass it as argument.
void removeFirst(SListNode head) --> void removeFirst() : the list knows what the first node is. It makes no sense to pass it as argument
Once you get the API right, you'll see that everything will be much easier to figure out, because you won't confuse the actual head of the list with the unnecessary head passed as argument.

Categories

Resources