• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting second data entry in node in a singly linked list, problem.  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to get a way to sort this singly linked list by the last names that have been entered into it. I thought I might try a bubble sort but I am having problems traversing the list by the second element and comparing. The list contains only 3 names right now as console entries but it should have 10 names when I am done. Any help would be greatly appreciated.

 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Edward Strife wrote:I am trying to get a way to sort this singly linked list by the last names that have been entered into it. I thought I might try a bubble sort but I am having problems traversing the list by the second element and comparing.

Because you keep overwriting your node; and since it only points forward, there's no way for you to go back to the start - which you will need to do many times to implement a bubble sort.

A few other things:
1. Don't start method names with capital letters.
2. Make ALL your fields private. ALWAYS. (or at least until you've learnt enough to know when not to do it.)
3. Your SLinkedList class actually defines a node of a linked list, not the list itself - which is, I think, where most of your problems are arising. You can do it the way you've defined it, but you're making life hard for yourself.

My advice: Rename that class SLLNode (or something similar), and add a new SLinkedList, something like:and move your main() method to that. I leave the rest of it up to you.

Finally: Have a look at the java.lang.Comparable interface, and have your node implement that. Then you can call compareTo() on the whole node, rather than on each String.

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!