Solved

inserting elements into a linked list

Posted on 2003-11-13
90
5,040 Views
Last Modified: 2013-12-14
First of all I dont want to use any of the APIs related to Lists or any kind of data struct.

Here is the code(Let me type it):

public class StringList()
{
    private LinkedListNode head=null;
    public void addString(String initString)
    {
           LinkedListNode newNode=null;
           newNode=new LinkNode(initString, newNode);
           
            if(head==null)
            {
                 head=newNode;
             }                                                          
     
            else
             {
                   //Here must add elements to the list and create the list whenever this method is      
                  // called witout altering the previous contents of the list.(I have trouble here).
             }
        }                                                                        
                                                                       
         
            private class LinkedListNode
  {
      private String data;
      private LinkedListNode next;

      public LinkedListNode(String initData, LinkedListNode initNext)
      {
          data = initData;
          next = initNext;
      }

      public String getData() { return data; }
      public LinkedListNode getNext() { return next; }

      public void setData(String changeData)
      {
          data = changeData;
      }

      public void setNext(LinkedListNode changeNext)
      {
          next = changeNext;
      }
     
   }
}            
                                                   
                                           
How do I keep adding the data to the list whenever "addString(arg)" method is called by another program.I have already added an object to head. But after that how do I keep adding new initStrings whenever "addString(arg)" is called.Thanks a lot.
                                               
                                                     

                                             
                                                                                     
                                                                                                           
                                                                                     
     
0
Comment
Question by:b_vishwajit
  • 37
  • 33
  • 14
  • +2
90 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742297
You're getting a bit confused here: you should have

a. a Node class
b. a LinkedList class
c. an Object field in Node
d. A Node field in Node called 'next'

The String would be assigned to c at the head. Then you'd need to set the next reference when you added a new Node.
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9742316
Well you would need to add the newly created node to the end of the list.  This takes two steps:

1) Move to the end of the list
2) Add the new node there

You may want to consider initializing the next variable inside LinkedListNode to null instead of to itself, but you can still solve your problem the way you have it now.
To move to the end of the list, do something like:

LinkedListNode pos = head;
while(pos.next != pos)
  pos = pos.next;

The above code will move you to the end of the list.  Now you need to add the new node to the end:
pos.next = newNode;
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9742335
>>a. a Node class
My res: LinkedListNode.

>>b. a LinkedList class
My res: StringList
>>c. an Object field in Node
My res: String data;

>>d. A Node field in Node called 'next'

My response:LinkedListNode next.
CEHJ I have done everything properly. I am just unable to add things to the list.
0
 
LVL 92

Expert Comment

by:objects
ID: 9742380
Here's a linked list example that may be helpful as a reference.
0
 
LVL 92

Expert Comment

by:objects
ID: 9742413
If you add the new node to the head of the list then you can simply use:

   public void addString(String initString)
    {
           head=new LinkedListNode(initString, head);
        }                              
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9742417
>But after that how do I keep adding new initStrings whenever "addString(arg)" is called.
it depends where do you want to insert a new node - at the begining of the list, or at the end.
   if at the begining:
..................
         newNode.setNext(head); //link to next
         head=newNode;
 .....................
     , if at the end see lwinkenb's answer.
 
Regards. :)
0
 
LVL 92

Expert Comment

by:objects
ID: 9742421
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9742442
by the way, if you have any troubles with list structures, you can alway see Sun realization of it in source code. It's a good example.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742458
Yes, looking more closely at your code again it seems to be mostly there, although i'd use an Object reference, not String, for the data field as then it's more reusable.

You can take the approach suggested by lwinkenb, but since you seem to be making a reference to the head, you can do as follows

void add(Object o) {
  LinkedListNode node = new LinkedListNode();
  node.data = o;
  if (head != null) {    
    head.next = node;
  }
  head = node;
}


   
    head.data = o;
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742473
Something odd crept in at the end there ;-)

Obviously you can use it to add Strings

list.add("XXX");
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9742480
dualsould if I add at the begining what happens to the previous head?
I guess:
whenever i am trying to add a string, this.string becomes head and the previous head becomes next node in the list.Now string is pointing to the next node in the list.So every time I call addString, I am creating a list by pushing down each element in the list by (one index).

lwinkweb

pos.next creates a nullpointer exception.Hence your trick does not work.


I also want to write a method toString() which can return the whole list.But first let me create the list.I will try dualsouls trick and get back with some fdbk.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742487
>>If you add the new node to the head of the list then you can simply use...

What about the link between the old head and the new head?
0
 
LVL 92

Expert Comment

by:objects
ID: 9742518
> .I will try dualsouls trick and get back with some fdbk.

Thats exactly what the code I already posted does :)
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9742521
It looks like dualsouls suggestion is working. I will get back after approximately 1:30 hrs . I have an arts class now(which realy is boring and I go there for attendance sake).This is realy great fdbk by all of you. CEHJ your suggestion is also cool.I will get back later.
0
 
LVL 15

Expert Comment

by:dualsoul
ID: 9742533
>whenever i am trying to add a string, this.string becomes head and the previous head becomes next node in the list.Now string is pointing to the next node in the list.So every time I call addString, I am creating a list by pushing down each element in the list by (one index).

yes. exatly :), it's if you want to add new String at the beggining of list (new head). if at the end this is correct for lwinkenb's code:
............................
LinkedListNode pos = head;
while(pos.next != null)  //null indicates end of list i think
  pos = pos.next;
.............................
0
 
LVL 92

Expert Comment

by:objects
ID: 9742541
public void addString(String initString)
{
      head=new LinkedListNode(initString, head);
}      

public String toString()
{
   StringBuffer result = new StringBuffer();
   LinkedListNode next = head;
   while (next!=null)
   {
      result.append(next.getData());
      result.append(" ");
      next = next.getNext();
   }
   return result.toString().trim();
}
0
 
LVL 92

Expert Comment

by:objects
ID: 9742558
> CEHJ your suggestion is also cool.

Except that it doesn't work :)
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9742687
Ahh yes, I see now that you are initializing next to null and not to itself.  In which case as dualsoul pointed out change my line
while(pos.next != pos)
to
while(pos.next != null)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742975
You could also keep a reference to the tail for convenience:

  void add(Object o) {
    LinkedListNode node = new LinkedListNode();
    node.data = o;
    if (head != null) {
      head.next = node;
    }
    head = node;
    if (tail == null) {
      tail = head;
    }
  }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9742999
>>Except that it doesn't work :)

Meaning what pray? ;-)

I can iterate and print the nodes quite successfully using my code

(whereas yours overwrites head ;-))
0
 
LVL 92

Expert Comment

by:objects
ID: 9743035
> You could also keep a reference to the tail for convenience

What convenience exactly???
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743063
It can help to know where both ends of the list are :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 9743094
> It can help to know where both ends of the list are :-)

Only one end is of use that I can see.

> (whereas yours overwrites head ;-))

Of course it does, what's your point?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743454
>>what's your point?

What happens to the next reference of the previous head node?
Your code should be as follows, as far as I can see ;-)

public void addString(String initString)
{
       LinkedListNode n = new LinkedListNode(initString, head);    
      head.next = n;
      head = n;
}      
0
 
LVL 92

Expert Comment

by:objects
ID: 9743542
> What happens to the next reference of the previous head node?

nothing

> Your code should be as follows, as far as I can see ;-)

No that code won't work, and the code I posted works fine anyway so I'm not sure what you don't understand about it.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743665
Perhaps i've maligned you - i was reading your code alongside thinking of the problem in a more generic way, as i think that's probably a better approach and was kind of encouraging b_vishwajit in that direction.

But that makes two of us, as my code works fine too [*and* you started it] ;-)
0
 
LVL 92

Expert Comment

by:objects
ID: 9743692
> as my code works fine too

Suggest you do some more testing :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743756
/**
 *Description of the Class
 *
 * @author     CEHJ
 * @created    13 November 2003
 */
public class Liszt {

  LinkedListNode tail;
  LinkedListNode head;

  /**
   * Test it. Add and print the capital letters
   * of the alphabet
   *
   * @param  args  The command line arguments (not used)
   */
  public static void main(String[] args) {
    Liszt l = new Liszt();
    for (char x = 'A'; x <= 'Z'; x++) {
      l.add(new Character(x));
    }
    l.iterativePrint();
  }

  /**
   * Add an object to the list
   *
   * @param  o  The object to add
   */
  void add(Object o) {
    LinkedListNode node = new LinkedListNode();
    node.data = o;
    if (head != null) {
      head.next = node;
    }
    head = node;
    if (tail == null) {
      tail = head;
    }
  }

  /**
   * Iterate the list, printing
   */
  void iterativePrint() {
    LinkedListNode n = tail;
    if (n == null) {
      return;
    }
    System.out.println(n.data);
    while ((n = n.next) != null) {
      System.out.println(n.data);
    }
  }

  /**
   * A linked list node holding a data field
   *
   * @author     CEHJ
   * @created    13 November 2003
   */
  class LinkedListNode {
    LinkedListNode next;
    Object data;
  }
}

0
 
LVL 92

Expert Comment

by:objects
ID: 9743795
Your original code (which is what we are talking about) just used head (which you now appear to ignore). I thought tail was just added for 'convenience'. Looks more like a bizarre bug fix :-D
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743834
'Convenience' in that in the original scope of the question ('how can i add nodes etc.') it is non-essential. To do any proper work with it, of course, (such as iterating) it *is* essential to know where the list begins.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9743836
So far everything is working nice except that head is being eaten up by toString() method.Here is my toString() method (and I know the mistake too, and also thinking of many ways to fix it).Can some one tell me whats wrong with this method?Thx




public String toString()
  {
    String str="";  
   
     if(head!=null)
     {
           
          LinkedListNode currentN=head;
            int i=1;
            for(;currentN.getNext()!=null;currentN=currentN.getNext())
            {
                  
                  str+="\n"+i+".\t"+currentN.getData();
                  i++;
            }
                                     return str;
    }
}      
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9743870
Ok I am have used toString() method posted by objects.It is perfect except that it is using StringBuffer (which i think should be ok since StringBuffer is not any kind of data structure).Objects you rule dude. CEHJ's suggestions are more generic(dynamic too) and  hence his answers are also good.CEHJ looks like java is your niche (as my prof says java is his niche).But Es stay with me. I still have to do a lot (but they are easy except one method in which I am supposed to write a method to remove an element from a list at the specified index.).
0
 
LVL 92

Expert Comment

by:objects
ID: 9743877
> it *is* essential to know where the list begins.

But you don't use head at all in your iteration. head is where the list begins isn't it.

0
 
LVL 92

Expert Comment

by:objects
ID: 9743885
> I am supposed to write a method to remove an element from a list at the specified index.

Start at head and and traverse your list the number of times specified by the index.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743908
>>But you don't use head at all in your iteration

head is where the iteration finishes

I guess it's a matter of semantics - i can't remember whether the 'classic' way is the other way around or not ;-)
0
 
LVL 92

Expert Comment

by:objects
ID: 9743937
> head is where the iteration finishes

So you iterate from the back of the list to the front.
And doesn't explain the purpose of the 'head' variable?
Or explain how you would iterate using your original code.
0
 
LVL 92

Expert Comment

by:objects
ID: 9743948
b_vishwajit> It is perfect except that it is using StringBuffer

StringBuffer was used for performance reasons, you could use String if required.

public String toString()
{
   String result = "";
   LinkedListNode next = head;
   while (next!=null)
   {
      result += next.getData();
      result += " ";
      next = next.getNext();
   }
   return result.trim();
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9743953
>>Or explain how you would iterate using your original code.

Wouldn't be able to - see my previous comments
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9743967
Ok everything looks fine. Now I have started typing code for other methods.Just stay along.
0
 
LVL 92

Expert Comment

by:objects
ID: 9743976
> Wouldn't be able to - see my previous comments

He see's the light. As I originally said, it doesn't work.

And you can get rid of the head variable in your fixed version.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9744010
I also mentioned that StringBuffer is ok and in fact better than String.

Another question??? When the list is printed out using to string method i have formatted it to look like:

1.String1
2.String2.
3.String3.
4.String4
etc..
and I have a counter which keeps track of number of elements in the list.

Now my problem is I have to write a method getString(int index) method which returns the String obj at the specified index.How do I do this? I am completely blank at this moment and going throught my textbook.
0
 
LVL 92

Expert Comment

by:objects
ID: 9744020
Though my code is so much neater :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 9744028
b_vishwajit>  I have to write a method getString(int index) method which returns
b_vishwajit> the String obj at the specified index.How do I do this?

Start at head and and traverse your list the number of times specified by the index.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9744056
>>As I originally said, it doesn't work.

Works fine - you just can't iterate. That was not an original requirement, although I agree you can't do much useful with it otherwise.

It's quite legitimate to keep a reference to the beginning and end of the list.

>>So you iterate from the back of the list to the front.

No. I iterate from the first element that was added to the list to the last element that was added - just as the API classes do
0
 
LVL 92

Expert Comment

by:objects
ID: 9744111
> Works fine - you just can't iterate.

ROTFL. Then why maintain links at all. It's supposed to be a linked list ie. nodes are linked.

Not sure on your definition of 'works' but that code seems fairly useless to me.

> It's quite legitimate to keep a reference to the beginning and end of the list.

legitimate maybe, but pointless.
Which is highlighted by the fact that you only ever use one of the references.

Enough of this though, it seems you understand the problem with that code now.


0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Author Comment

by:b_vishwajit
ID: 9744222
Here is my getString(int  ind) method which returns list element at the specified index.If there are any errors in it please post it immediately.The code is working perfectly.
      public String getString(int index)
      {
            String st="";
            int n=1;
            ListNode next=head;
            while(n<=index)
            {
                  st=next.getData();
                  next=next.getNext();
                  if(n>index)
                  st=next.getData();
                  
                  n++;
            }
                  return st;
      }
      
0
 
LVL 92

Expert Comment

by:objects
ID: 9744274
try something like:

public String getString(int index)
{
   ListNode node=head;
   for (int i=0; node!=null && i<n; i++)
   {
      node = node.getNext();
   }
   return (node==null ? null : node.getData());
}
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9744303
Ok that makes it compact objects. But is there anything wrong with my code. Now I will stop at this point. I am left with two more methods which I guess I will try to implement in train while going home. I have to catch the next train and go home from my school. It takes around 1 hour to get home and then I will relax for may be 1:30 minutes. So I will post my implemented new methods at midnight.Catch ya later then!!!!!!!
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9744320
Ok something else popped up in my mind. I have to sort the list elements (which are strings). I was planning to copy the list elements into an array and then use insertion sort to sort the elements. But is there any better way to sort the String elements in my list. Thanks.
0
 
LVL 92

Expert Comment

by:objects
ID: 9744337
If index is 0 it will return "", shouldn't it return the value of head.
It'll also have problems if n exceeds the number of elements in the list.
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9744355
Sort the elements as you add them to the list.  That is, in your addString() method you can move down the list until you find an object that is greater value than the value you are adding.  Then add the new Node just before the greater one.  If you always add items in this fashion, your list will always have all the items in order.
0
 
LVL 92

Expert Comment

by:objects
ID: 9744360
> But is there any better way to sort the String elements in my list.

Depends if you want to sort the list, or maintain the list in sorted order.
If you want to maintain the list in sorted order then change you addString() method to insert new strings at the correct sort order location in the list. This way your list will always be sorted. I outlined how to use this approach in your previous question.

0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745414
Now I am working on sorting part and rest of the easy methods.Once I successfuly implment sorting, rest of the methods will take care of themselves(what i mean is they are very easy).I think I can carry on my own from this point. EE's E's are the best.If any of you is still working at your desk reply to this post. I will try objects and lwinkweb's suggestion for sorting the array elements(in fact that was exactly the idea that popped up in my mind, but i still haven't understoof SLL that clearly for they are highly abstract).But I have better picture of SLL now.I will get back again.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745468
I'm still here.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745495
cool objects I am still working on getString() method.what should be 'n' in the code that you posted for this method. I am totaly getting sleepy.Need to get some caffeine:).
0
 
LVL 92

Expert Comment

by:objects
ID: 9745505
oops, 'n' should have been 'index' :)
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745512
objects,
              How about this getString() method?definitely better before the previous one:
              if((index>=0)&&(index<count))
            {
            try
            {
            while(n<=index)
            {
                  st=next.getLastName();
                  next=next.getNext();
                  if(n>index)
                  st=next.getLastName();
                  
                  n++;
            }
            }
            catch(NullPointerException err){System.out.println();}
            }
            
            
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745514
I forgot to mention "count" is the number of elements in my list.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745533
Won't that still have the same problem when index is 0.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745541
objects index 0 returns the first element in the list. 1 returns the second element and so on. But if it is index=numofelements in the list then getString() method returns nothing. I dont see any reason as to why it is wrong.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745553
If index is 0, and n is initially 1, then the while loop will not get entered.
Easy enough to test though, I'd suggest setting up a test program to exercise your list if you haven't already.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745556
Ok objects I implemented getString() just using the code you posted.Now I will start the sorting part(once i am done with this I can relax like hell:)).
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745573
>>Easy enough to test though, I'd suggest setting up a test program to exercise your list if you haven't already.

Actualy I changed value of n to 0 and forgot to mention that.Any how every time I write a new method I am testing my methods with a driver.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745603
Object are you still there? I am not getting any ideas about sorting (thought its easy).I know I have to implement a loop and then determine the position of the newNode and then insert it in the determined position.But how do I implement this part of the code? If you are still there please reply ASAP. I am getting lot of sleep.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745614
Have a look at the toString() method, it loops thru all the items in the list.
What you want to do in addString() is loop thru all the items *until* you find an element that is greater than the one you want to insert. That is then your insert position.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745675
so it is something like:

      newNode.setNext(head); //link to next
              
                    while (newNode!=null)
                    {
                        if((newNode.getLastName().compareToIgnoreCase(newNode.getNext().getLastName()))<0)
                       head=newNode;  
                       
                       newNode = newNode.getNext();
                }

this is not correct still thinking about it.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745705
oho ignore the previous code. it is totaly stupid.
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 9745708
I find it useful to draw yourself a diagram of your list to see what needs to be done to handle an insert:
eg. if you have the following list:
B -> F -> M -> X

And you add the node 'J', it will go between F & M:
B -> F -> ( J -> ) M -> X

So F.next will need to change from M to J
And J.next will need to set to M (which was the previous value of F.next).

And then you'll need to consider the special case scenarios where nodes are added at beginning and end of list.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745715
How about this one?

                                                ListNode next = head;
                  newNode.setNext(next);
                    while (next!=null)
                    {
                        if((newNode.getData().compareToIgnoreCase(next.getData()))<0)
                        {      
                              next=newNode;
                              break;
                        }
                       next = next.getNext();
                 
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745726
But how do I determine where J goes using a method like compareToIgnoreCase().I am a bit confused about this.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745736
> But how do I determine where J goes using a method like compareToIgnoreCase().

When you compare J to M, it will be less than M so you know the new node needs to go before M.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745764
It'd be something like the following (there are a few blanks for you to fill in)

ListNode pos = null;  // node to insert new node after
ListNode next = head;

while (pos==null && next!=null)
{
   String s = next.getData();
   ListNode nextplusone = next.getNext();

   if (nextplusone==null)
   {
      // end of list

      pos = next;
   }
   else if (node goes between next and nextplusone)
   {
      pos = next;
   }

   next = nextplusone;
}

// now insert node after 'pos', if pos is null insert at start of list
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745803
But what happened to newNode.I am estranged from my conventions?????
0
 
LVL 92

Expert Comment

by:objects
ID: 9745817
Nothing happened to it, it'll be used in the gaps I didn't complete.
You actuall don't even need to create it until after you have determined where it needs to be inserted.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745836
in the else if blank field i did it like this
else if (((newNode.getData().compareToIgnoreCase(next.getData()))<0)&&
       ((newNode.getData().compareToIgnoreCase(nextplusone.getData()))>0))

// now insert node after 'pos', if pos is null insert at start of list
      if(pos==null)
                pos=newNode;
      else
      pos.setNext(newNode);            
                        
I am sure about the else-if blank field but not the last one.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745860
// end of list
here i guess i should insert pos.setNext(null); since it is the end of the list.
0
 
LVL 92

Expert Comment

by:objects
ID: 9745877
if pos is null then the new node will need to be inserted at the head of list.
ie. it will become the new 'head', and it will have the old head as its next
(A -> ) B

otherwise the newnode will have it's next set to what pos is pointing to, and pos will point to the new node (as you have done).
0
 
LVL 92

Expert Comment

by:objects
ID: 9745882
> here i guess i should insert pos.setNext(null); since it is the end of the list.

Not necessary, you can handle the insertion once the loops finished and you have the pos.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745913
This is what you mean:

      if(pos==null)
      {
            newNode.setNext(next);
            next=newNode;
                        
      }
      else
      {
            pos.setNext(newNode);
            newNode=pos;            
      }
If you want me to paste the whole addToList(String str) method I can do it ,in case if you want to know what exactly i am doing.If i am not close enough.Then I will go to sleep may be getting sleep will help.It is already 3:30 at midnight.                  
0
 
LVL 92

Expert Comment

by:objects
ID: 9745926
Still awake :)
Try something like:

     if(pos==null)
     {
          newNode.setNext(head);
          head=newNode;
     }
     else
     {
          newNode.setNext(pos.getNext());
          pos.setNext(newNode);          
     }
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9745948
That works but elements are arranged in reverse order.For ex
if List elements are B C H after sorting the elements will be H C B. Some silly bug somwhere.

Here is my updated addToList:(getData() is removed by getLastName())



public void addToList(String lName)
      {
            ListNode newNode=null;
            newNode=new ListNode(lName, newNode);
            
            if(head==null)
            {
                  head=newNode;
                  count++;
            }
            else
            {
            
                  ListNode pos = null;  // node to insert new node after
                  ListNode next = head;

                  while (pos==null && next!=null)
                  {
                          String s = next.getLastName();
                          ListNode nextplusone = next.getNext();

                          if (nextplusone==null)
                          {
                             // end of list

                             pos = next;
                          }
                      else if (((newNode.getLastName().compareToIgnoreCase(next.getLastName()))<0)&&
                                       ((newNode.getLastName().compareToIgnoreCase(nextplusone.getLastName()))>0))
                     {
                       pos = next;
                     }

                     next = nextplusone;
                   }

                        if(pos==null)
                      {
                           newNode.setNext(head);
                           head=newNode;
                            }
                      else
                {
                     newNode.setNext(pos.getNext());
                     pos.setNext(newNode);          
                }

                  
                  
            }
      }
      
0
 
LVL 92

Expert Comment

by:objects
ID: 9746002
try switching the < and > around, and you better make one include equals to handle if an existing string is passed in:

else if (((newNode.getData().compareToIgnoreCase(next.getData()))>=0)&&
       ((newNode.getData().compareToIgnoreCase(nextplusone.getData()))<0))

It's beer o'clock here, so I'll talk to u tomorrow :}
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9748262
lol.ok. But what do you mean when you say:
>>better make one include equals to handle if an existing string is passed in:
you mean remove this statment:
if(head==null)
         {
              head=newNode;
              count++;
         }
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9748282
>>>>better make one include equals to handle if an existing string is passed in:
Never mind I have understood what you mean by that.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9748302
I switched made changes to that statement in various ways. The result is still same.This weird!!!!!!!!!!.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9750519
Objects whats wrong with sorting.Its annoying please reply. Thx.
0
 
LVL 92

Expert Comment

by:objects
ID: 9751387
I just tested the original addString() method you posted in the comment containing:
> Here is my updated addToList:(getData() is removed by getLastName())

And it worked fine, sort order was B C H.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9752171
Test it with more than 3 elements like 10 elements.Never mind I will figure it out. You get all the points for your patience and help.You have been of great help "objects".Hope you will be around EE when I post a question in this area.Thanks.
0
 
LVL 5

Author Comment

by:b_vishwajit
ID: 9752195
And also try to change the order of the elements and algorithm fails to work.
0
 
LVL 92

Expert Comment

by:objects
ID: 9752686
Thanks for the points :-)

http://www.objects.com.au
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now