문제

I am having issues storing data typed in the keyboard to my link list Add method. The point of this program is to implement a queue using a linked list. The only thing is, that the class constructor accepts two parameters for every node in the list (their Name and link).

here is my class file so far...

public class linklist_MP
{
 //Private intance variables and links
   private linklist_MP front;
   private linklist_MP rear;
   private linklist_MP link;
   private linklist_MP previous;
   private String data;
   private int count = 0;
   private boolean flag;



//Construtor for Each Node's link and parameter type
  public linklist_MP(String input, linklist_MP intiallink)
  {
  data = input;
  link = intiallink;

  }

public boolean listEmpty()
{
  flag = false;

  if(count == 0)
  {
     flag = true;
  }

  return flag;
}

public void addList(String input)
{
  //Creating new node with read input
  //linklist_MP node = new linklist_MP(input, null);

  if(count == 0)
  {
      front = new linklist_MP(input, front);
  }
  else
  {
     previous = front;

     while(previous.link != null)
     {
        previous = previous.link;
     }

     rear = previous;

     rear.link = new linklist_MP(input, null); 

  }


  count++;

}

 public String toString() 
 {
   String result = data + " ";
   if (link != null) 
   {
      result += link.toString();
   }
   return result;
 }
}

And Here is my Driver File which makes a object of my class and stores in the user data..

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;

public class linklistDriver_MP
{
 public static void main(String[] args)
 {

  String input;

  Scanner keyboard = new Scanner(System.in);


  System.out.println("Just add a String: ");
  input = keyboard.nextLine();


  linklist_MP object = new linklist_MP(input, null);

  object.addList(input);

  System.out.println("Add another String: ");
  input = keyboard.nextLine();

  object.addList(input);

  System.out.println("\nTime to print the list out: ");
  object.toString();
 }
}

Basically when my print method is called in the driver file to print all the nodes in the link list, nothing comes out and the list prints blank. I am trying to figure out why that is since I used the object in my driver to add the two strings the user enters in the keyboard as the add method is called... Thanks in-advance!

도움이 되었습니까?

해결책

The reason your program does not output anything is because you call the method toString() but you never print the output of this method.

However it looks as if your linked list structure is also way off. Essentially a linked list data structure consists of a piece of data and a link to the next node in the sequence.

You however have multiple other nodes linked in your node. You should try to simplify your design because a linked list is a very simple data structure but I think you have overcomplicated it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top