Advertisement
Guest User

Untitled

a guest
Apr 10th, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. public class InsertList {
  2.  
  3.     private static class ListElement {
  4.         int value;
  5.         ListElement next;
  6.  
  7.         public ListElement(int v){
  8.             value = v;
  9.         }
  10.     }
  11.  
  12.     public static ListElement insertList(ListElement head, ListElement elem){
  13.         if (head == null || elem.value > head.value){
  14.             elem.next = head;
  15.             return elem;
  16.         }
  17.         else {
  18.             head.next = insertList(head.next, elem);
  19.             return head;
  20.         }
  21.     }
  22.  
  23.     static void printList(ListElement head){
  24.         System.out.println("List:");
  25.         for (ListElement i = head; i != null ; i = i.next)
  26.             System.out.println(i.value);
  27.     }
  28.    
  29.     public static void main (String args[]) {
  30.         ListElement head = null;
  31.         head = insertList(head, new ListElement(5));
  32.         printList(head);
  33.         head = insertList(head, new ListElement(3));
  34.         printList(head);
  35.         head = insertList(head, new ListElement(1));
  36.         printList(head);
  37.         head = insertList(head, new ListElement(2));
  38.         printList(head);
  39.         head = insertList(head, new ListElement(8));
  40.         printList(head);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement