title: Delete Last Node of a Linked List
body: <p>I am practicing working with Linked List Nodes and have come upon a problem I don't know how to answer. How do you go about deleting the last node in a linked list. The code below works for all entry's bar the last node. The last does not get deleted.</p>
  
  <p>Node Class</p>
  
  <pre><code>public class Node {
  
      private String data;
      private Node next;
  
      Node(String data, Node next)
      {
          this.data = data;
          this.next = next;
      }
  
      public void setData(String d)
      {
          data = d;
      }
  
      public void setNext(Node n)
      {
          next = n;
      }
  
      public String getData()
      {
          return data;
      }
  
      public Node getNext()
      {
          return next;
      }
  </code></pre>
  
  <p>Main</p>
  
  <pre><code>Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
          list = insertSecond(list,"New Node");
          list = addLast(list,"LAST NODE");
  
          printList(list);
          System.out.println();
          deleteNode(list,"LAST NODE");
          printList(list);    
      }
  
      public static Node deleteNode(Node list,String str)
      {
          Node temp = list;
          Node prev = list;
  
          while(temp.getNext() != null)
          {
              if(temp.getData().equals(str))
              {
                  if(prev.getNext() == null)
                      prev.setNext(null);
                  else{
                  prev.setNext(prev.getNext().getNext());
                  }
  
              }
              prev = temp;
              temp = temp.getNext();
          }
  </code></pre>