University of Toronto
Department of Computer Science
csc 148: Introduction to Computer Science

Linked Data Structures (continued)

In both of those problematic test cases, the the new node must be added to the front of the list. Our code doesn't work in those cases; head is not set to point to the new node. We can fix this problem by checking to see if the new node is to be added to the front of the linked list, and handling that case separately.

   public class LinkedList {
       Node head;

       public void insert(int key) {
            Node current = head;
            Node previous = null;

            Node temp = new Node();
            temp.key = key;
            temp.link = null;

            while(current != null && current.key < key) {
                previous = current;
                current = current.link;
             }

             if(head == current) {
                 head = temp;
                 temp.link = current;

             } else if(current == null || current.key != key){
                 previous.link = temp;
                 temp.link = current;
             }
        }
  }

Now that you have seen how to implement insert, you are ready to try writing other linked list methods.

Exercise: Write a delete method.



PreviousPrevious    |   Home   |   Next Next