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

Linked Lists (continued)

The problem with the code is that when a new node is added to the front of the list, head is not set to point to the new node. To fix this problem we need to check to see if the new node is to be added to the front of the linked list.

   public class LinkedList {
       Node head;

       public 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, use the same steps to implement the delete method.



PreviousPrevious    |   Home   |   Next Next