linked list - Writing a method to sort a singly linkedlist in ascending order (java) -


the method 'insertascending' gives me first number after enter new ones. can i'm doing wrong? thanks.

public class linkedlist13 { // private inner class node

private class node{     int data;     node link;       public node(){         data = integer.min_value;         link = null;     }      public node(int x, node p){         data = x;         link = p;     } } // end of node class  public node head;  public linkedlist13(){     head = null; }  public void insertascending(int data){      node node = new node();     node.data = data;       if (head == null)          head = node;      node p = head;       while (p.link != null)      {          if (p.link.data > data)          { node.link = p.link;            p.link = node;            break;          }          p= p.link;      }    } 

}

first of all, should return after setting head of list (when first element added).

second of all, should handle case newly inserted node smallest in list (and therefore should come first). loop never compares added node head of list.

finally, if added element wasn't inserted in while loop, should inserted after while loop.

public void insertascending(int data) {     node node = new node();     node.data = data;      if (head == null) {         head = node;         return;     } else if (node.data < head.data) {         node.link = head;         head = node;         return;     }     node p = head;      boolean added=false;     while (p.link != null)     {         if (p.link.data > data)         {             node.link = p.link;            p.link = node;            added = true;            break;         }         p = p.link;     }     if (!added)          p.link = node; } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -