Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class InsertList {
- private static class ListElement {
- int value;
- ListElement next;
- public ListElement(int v){
- value = v;
- }
- }
- public static ListElement insertList(ListElement head, ListElement elem){
- if (head == null || elem.value > head.value){
- elem.next = head;
- return elem;
- }
- else {
- head.next = insertList(head.next, elem);
- return head;
- }
- }
- static void printList(ListElement head){
- System.out.println("List:");
- for (ListElement i = head; i != null ; i = i.next)
- System.out.println(i.value);
- }
- public static void main (String args[]) {
- ListElement head = null;
- head = insertList(head, new ListElement(5));
- printList(head);
- head = insertList(head, new ListElement(3));
- printList(head);
- head = insertList(head, new ListElement(1));
- printList(head);
- head = insertList(head, new ListElement(2));
- printList(head);
- head = insertList(head, new ListElement(8));
- printList(head);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement