I created a singly linked list , it giving below error . not sure what is wrong, ant suggestion
Error/ OP - List is javaTest.LinkedListcreation#1540e19d
I am not sure what this value in Output is meant for .
Process finished with exit code 0
public class LinkedList{
public static void main (String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
System.out.print("List is " + L1);
}
}
class LinkedListcreation {
int listcount;
node head;
LinkedListcreation() {
head = new node(0);
listcount=0;
}
node Temp;
void addNodeAtEnd(Object d){
node Current = head;
Temp = new node(d);
while (Current.getNext()!= null){
Current = Current.getNext();
}
Current.setNext(Temp);
listcount++;
}
}
class node {
Object data;
node next;
node(Object d) {
next = null;
this.data=d;
}
node(Object d, node nextNode) {
next = nextNode;
this.data=d;
}
public Object getdata(){
return data;
}
public void setdata(int d){
data = d;
}
public node getNext(){
return next;
}
public void setNext (node nextValue){
next = nextValue;
}
}
Your code is all right, but in order to print useful information about an object (your list in this example), you need to override the toString method in your LinkedListcreation class.
For example:
public String toString() {
return "List with " + this.listcount + " nodes.";
}
As everybody said, you have to override toString(). Here you have the right implementation:
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(head.data.toString());
node n;
while(n = head.getNext() != null)
sb.append(", " + n.data.toString());
sb.append("]");
return sb.toString();
}
you are trying to print the list object rather than the element which you have added and more over what you see is not error. check about toString() method in java to understand the output which you see.
Modify your main() as below to see the element you added.
public static void main (String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
System.out.print("List is " + L1.head.next.data);
}
output : List is 1
Your code does not have any error. If you want to print the nodes in your list you just have to add another function in you LinkedListcreation class which will iterate over your list and print each node's data. Add this block in your LinkedListcreation class.
public void printList(){
node current = head.next;
while(current!=null){
System.out.println("node's data is: "+ current.getdata());
current = current.getNext();
}
}
Also in your main function call the above mentioned function using your list's object L1.
L1.printList();
The code has compiler errors. Try corrected code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class LinkedList
{
static void Main(String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
Console.WriteLine("List is " + L1);
}
}
public class LinkedListcreation
{
int listcount;
node head;
public LinkedListcreation()
{
head = new node(0);
listcount = 0;
}
node Temp;
public void addNodeAtEnd(Object d)
{
node Current = head;
Temp = new node(d);
while (Current.getNext() != null)
{
Current = Current.getNext();
}
Current.setNext(Temp);
listcount++;
}
}
public class node
{
Object data;
node next;
public node(Object d)
{
next = null;
this.data = d;
}
node(Object d, node nextNode)
{
next = nextNode;
this.data = d;
}
public Object getdata()
{
return data;
}
public void setdata(int d)
{
data = d;
}
public node getNext()
{
return next;
}
public void setNext(node nextValue)
{
next = nextValue;
}
}
}
Related
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
I am attempting to implement a linked list that uses a node class containing head, tail, and current nodes. Part of the linked list is an add method that should add a value to the end of the current node in the list just like an actual linked list would. My issue is that it only works for the first node and then just stops there. For example, in my main I tried testing the code by calling add(1); and add(2);. The console shows me 1 but that's all. I'm unsure if the error is in my add method, toString method, or node class.
I'll also add that I tested whether the correct values were being assigned to "current" in either case, and they were. This has led me to wonder if it's the toString that is the root of the issues, however no matter how much I try I can't change it to make any improvements.
I've hoping fresh eyes may be able to find any blaring issues that may exist.
Add method:
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
Node class:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
toString:
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
All:
public class IntLList extends IntList{
public IntLList(){
}
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
Node head = null;
Node tail = null;
Node current = null;
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
public int get(int index){
return 0;
}
public void set(int index, int val){
}
public void remove(int index) throws ArrayIndexOutOfBoundsException{
}
public int size(){
return 0;
}
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
return "temp";
}
public void removeLast(){
}
public boolean isEmpty(){
boolean isEmpty = false;
if(head == null){
isEmpty = true;
}
return isEmpty;
}
public void clear(){
}
public static void main(String[] args) {
IntLList i = new IntLList();
i.add(1);
i.add(2);
i.toString();
}
}
Make the following changes:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = NULL; // this is to set the next node of current node to null
if(next!=NULL)
next.next=this; // this is to set the previous node to point to current node
}
}
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
Ok guys I need to write a method; MyLinkedList getFirst(int n) – Returns a linked list of the first n elements. If the list is empty or n > size return null.
and I'm lost, I've done the mothods add, remove, add to middle, print a string of elements, and so on but this one has me stuck..
all I have so far is:
public MyLinkedList<E> getFirst(int n) {
if(n > size ) {
return null;
}
Node<E> current = head;
for (int i = 0; i == n; i++) {
current.next = new Node<E>(e);
}
}
I know this code is pretty wrong but its all I can think of been working on this assignment for a while and I'm just running out of steam I guess lol
Thanks for any and all help.
Create an empty list
Add the head to the list
Continuing adding the next node to the list until you have the first n nodes.
public MyLinkedList getFirstN(int n) {
MyLinkedList firstNList=new MyLinkedList();//create an empty list
if(n>size)
firstNList= null;
else {
Node tmp=head; //initialise tmp Node to the head(beginning) of list
for(int i=0;i<n;i++) {
firstNList.add(tmp);//add current node to the end of list
tmp=tmp.getNext();
}
}
return firstNList;
}
Implement the add(Node node) method to append a Node to the end of list.
You can use this as prototype and proceed with any operation
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
public class LinkedList {
private Node start;
public LinkedList() {
start = null;
}
public void insert(int x) {
if(start == null) {
start = new Node(x, start);
} else {
Node temp = start;
while(temp.getNext() != null) {
temp = temp.getNext();
}
Node newNode = new Node(x,null);
temp.setNext(newNode);
}
}
public void getFirst() {
if(start == null) {
System.out.println("\n List is empty !!");
}
else {
Node temp = start;
System.out.println("\n First Element is --->" + temp.getData());
}
}
}
public class MainClass {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("\n--- Inserting 100 ---\n");
ll.insert(100);
ll.insert(101);
ll.insert(102);
ll.insert(103);
System.out.println("\n--- First Element ---\n");
ll.getFirst();
}
}
I thought I had this program working but unfortunately I've overlooked something. How do you delete the first Node and convert the second node into the front of the Linked List. I've tries a multitude of approaches but end up with the same result.(LinkedList remaining unchanged) Any guidance would be much appreciated.
Node Class
public class Node {
private String data;
private Node next;
Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
Main
public static void main(String[] args) {
Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
list = insertSecond(list,"New Node");
list = addLast(list,"LAST NODE");
printList(list);
System.out.println();
deleteNode(list, "NODE 1");
printList(list);
}
public static Node deleteNode(Node list,String str)
{
Node temp = list;
Node prev = list;
while(temp != null)
{
if(temp.getData().equals(str))
{
if(temp.getData().equals(list.getData()))
{
list = list.getNext();
return deleteNode(list,str);
}
else
{
prev.setNext(prev.getNext().getNext());
}
}
prev = temp;
temp = temp.getNext();
}
return list;
Your deleteNode function should return the head of new list. This is required only in one edge case which you described - deleting head of that list.
list = deleteNode(list, str);
Also you don't need to recursively execute deleteNode method, iteration over node elements should be enough:
public static Node deleteNode(Node list, String str) {
// I'm assuming that you are deleting the first inscance of the string
Node temp = list;
Node prev = list;
while(temp != null) {
if(temp.getData().equals(str)) {
if(temp.getData().equals(list.getData())) {
return list.getNext();
}
else {
prev.setNext(temp.getNext());
return list;
}
}
prev = temp;
temp = temp.getNext();
}
return list;
}