Vivi  Xu
Vivi Xu

Reputation: 131

Confused by LinkedList

Guys I'm totally confused when I'm doing an example for LinkedList about displaying Birthday details,

My code is as follows:

import java.util.Iterator;
import java.util.LinkedList;


public class LinkedListTest {
public static void main(String[] args)
{
Birth[] birth = new Birth[10];
LinkedList list = new LinkedList();
for(int i = 0; i < 10; i++)
{
    birth[i] = Birth.BirthEntry();
    list.add(birth[i]);
}
Print(list);
list = LinkedSort(list);
Print(list);
}
public static LinkedList LinkedSort(LinkedList list)
{
for(int k = 1; k < list.size(); k++)
    for(int i = 0; i < list.size() - k; i++)
    {
        if(((Birth)list.get(i)).compareTo(((Birth)list.get(i + 1)))>0);
        {
            Birth birth = (Birth)list.get(i);
            list.set( i,  (Birth)list.get( i + 1));
            list.set(i + 1, birth);
    }
}
return list;
}
public static void Print(LinkedList list)
{
Iterator it = list.iterator();
System.out.println("-----------------------");
while(it.hasNext())
{
    System.out.println(it.next().toString());
}
System.out.println("---------------------------");
}
}

And I have a couple of questions needed to be clarified, thanks for your help in advance.

  1. What is the use here to declare k? The question corresponds to for(int k = 1; k < list.size(); k++)

  2. I have no idea why I need to declare this, I totally get confused here:

    list.set( i,  (Birth)list.get( i + 1));
    list.set(i + 1, birth);
    
  3. I got no run result except for "Input Birthday, Year: Month: Day: ". Is it because I have not input any data?

Upvotes: 1

Views: 79

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201419

There is a fairly substantial bug in your code, this

if(((Birth)list.get(i)).compareTo(((Birth)list.get(i + 1)))>0);
{
  Birth birth = (Birth)list.get(i);
  list.set( i,  (Birth)list.get( i + 1));
  list.set(i + 1, birth);
}

Does not work, because your if body is a single semi-colon. Then you have an anonymous block. Change it to,

if(((Birth)list.get(i)).compareTo(((Birth)list.get(k)))>0) // <-- no semicolon
{
  Birth birth = (Birth)list.get(i);
  list.set( i,  (Birth)list.get(k));
  list.set(k, birth);
}

Next, k starts at 1 so that i can start at 0 (it's a nested loop for a sort). Next, the size of the List is what controls the range of k. Next the instructions in your if body are to swap the element at i and the element at k if the element at i is greater then the element at k.

Finally, this

for(int i = 0; i < list.size() - k; i++) {

Should probably be

for(int i = 0; i < list.size(); i++) {
  if (i == k) continue;

Upvotes: 1

Related Questions