I have this code and I am trying to input numbers so I can sort them. Could someone help?

Code:

class ListSortExample
{
static class Node
{ int val; Node next;
Node(int v, Node t) { val = v; next = t; }
}
static Node create()
{ Node a = new Node(0, null);
for (In.init(); !In.empty(); )
a.next = new Node(In.getInt(), a.next);
return a;
}
static Node sort(Node a)
{ Node t, u, x, b = new Node(0, null);
while (a.next != null)
{
t = a.next; u = t.next; a.next = u;
for (x = b; x.next != null; x = x.next)
if (x.next.val > t.val) break;
t.next = x.next; x.next = t;
}
return b;
}
static void print(Node h)
{ for (Node t = h.next; t != null; t = t.next)
Sytstem.out.println(t.val + ""); }
public static void main(String[] args)
{ print(sort(create())); }
}

Dani AI

Generated

A few focused corrections and practical options to finish the example from . The In calls in the posted code (e.g. In.init(), In.getInt(), In.empty()) are not part of core Java — they come from the small I/O helper library bundled with Sedgewick’s Algorithms text and related algs4 support code. If that helper class isn’t on the classpath the program won’t compile; either add the book’s support library or replace those calls with standard Java I/O. (algs4.cs.princeton.edu)

Concrete fixes and a simple console alternative using Scanner (shorter than the BufferedReader example already posted by ):

static void print(Node h) {
    for (Node t = h.next; t != null; t = t.next)
        System.out.println(t.val);
}
static Node create() {
    Node head = new Node(0, null);
    Scanner sc = new Scanner(System.in);
    while (sc.hasNextInt()) {
        head.next = new Node(sc.nextInt(), head.next); // prepends like original
    }
    // avoid closing sc if System.in is needed elsewhere
    return head;
}

Use Scanner.hasNextInt() / nextInt() to detect EOF or send a sentinel. See the Java Scanner API for details. (docs.oracle.com)

If the code is used inside a Swing JFrame, don’t rely on System.in. Swing is event-driven: use JTextField, JOptionPane.showInputDialog, or read input on a background thread (SwingWorker) so the Event Dispatch Thread isn’t blocked — otherwise the UI will hang. The Oracle Swing tutorial covers safe concurrent patterns and EDT rules. (docs.oracle.com)

Small debugging checklist: fix the Sytstem typo, ensure create() returns the dummy head node (the sort routine expects a to be a head with a.next), test with a few known integers to verify ordering, and insert short System.out.println traces if nodes don’t link as expected. These checks complement ’s head/node advice and will reveal whether the problem was input, a typo, or GUI vs console I/O.

Recommended Answers

All 7 Replies

What you have here is a so-called "singly-linked list" data structure.

Basically, a singly-linked list is a collection of Node objects. Each Node object has two fields: a data field (often a String or integer, though really it could be anything - even another object), and a link field which "links" the Node object to one other Node object. Conceptually, what this looks like is:

o -> o -> o -> ... -> o
|    |    |           |
d    d    d           d
a    a    a           a
t    t    t           t
a    a    a           a

In this diagram, each circle is a Node. It has attached data (going vertically) and a link to another Node, which itself has attached data and a link to another Node, which itself has attached data and a link to another Node, and so on. The last Node in the chain has attached data, but a null link. The first Node is often called the "head" and the last Node is often called the "tail."
It looks like your main method tries to sort a linked list that is generated by the create() method. But now I'm confused - in the create() method, where did the ln variable come from? What is that?
And what, exactly, do you want to do with this thing?

Well, I got this code from a book and I need to insert some numbers in it and have this code sort the nodes. I know that they are linked list nodes... thanks for exlaining it.. i have a better concept of them know.
Anyways, I haven't taken Java for a while and I need to insert this code into a java program that inserts numbers, sort them, and finally ouputs the data.
Second, the 'In' variable was from the book and I don't even know where it came from... first I thought it would be System.In; just like System.out, but it is not... do you get what I mean?

I see. Where are these numbers coming from? Are they being read in from a file? Are they being typed in while the program runs (via a call to System.in)? Are they entered on the command-line when you call the program? The answer to this question determines how you will create your linked list.

As for how to sort and print it, observe that both the sort() and print() methods accept a single Node as the input. That Node is supposed to be the "head" or the first Node of the linked list. So, in the body of your program, keep track of just the head Node - you don't need to worry about the others because the head connects to the rest of the chain with its .next field. To print the list, just pass the head into print().

The sort() method looks a little funny to me. Is it broken? If I'm reading it correctly, you pass in the head Node, it creates a sorted copy of the list connected to the head, and it returns a new Node called b which is the head of the sorted copy. Yes? If that's the case, all you have to do is set your head Node equal to the value of sort(head), and your list will be sorted.

I hope that helps somewhat.

I see what you are talking about... I always used text boxes to insert text in classes. How would I insert the numbers using System.in? Could you help me out with this part. Thanks

Hi brian63304,

If you want to grab data from the keyboard via System.in, you're going to want to use a BufferedReader. The typical setup is this:

import java.io.*;
public class Something {
     public static void main(String[] args) throws Exception {
          InputStreamReader isr = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(isr);
          //--Now, to get a single line of text from the keyboard, just say:
          String input = br.readLine();
          //--To transform a String value into an integer value, say:
          int a = Integer.parseInt(input);
          //--To collect a bunch of integer values, run a while loop.
          //--Stop when the user enters a blank line or hits CTRL-D.
          //--Check for a blank line by checking the length of 'input'.
          //--Check for CTRL-D by checking to see whether input is null.
          //--Don't forget to close your BufferedReader:
          br.close();
     }
}

Every time you get a new number, build a Node for it. Then link the previous Node to this new Node by using the previous Node's .next field. Clear?

Ok.... I get the it to run but when I open the Jframe, I can not get it to run.

I finally worked out the problem... thanks for the info.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.