DeleteLast Function of a SinglyLinkedLast

This is a discussion on DeleteLast Function of a SinglyLinkedLast within the C++ Programming forums, part of the General Programming Boards category; I can't figure out how to fix this. I'm trying to move the pointer all the way to the end ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    36

    DeleteLast Function of a SinglyLinkedLast

    I can't figure out how to fix this. I'm trying to move the pointer all the way to the end of the list but it won't even run. It builds fine, no compiler errors, just doesn't run. It freezes execution.

    Code:
    		void SinglyLinkedList::DeleteLast( ){
    
    			Node* newNode1 = new Node;
    			Node* newNode2 = new Node;
    			Node* deleteNode = new Node;
    
    			newNode1 = first;
    
    			if(Length() == 0)
    				cout << "List is empty." << endl;
    
    			else if(Length() == 1)
    				DeleteFirst();
    
    			else
    				while(newNode1->next != NULL || newNode2->next != NULL){
    					newNode2->next = newNode1->next;
    					newNode1->next = newNode2->next;
    				}
    
    				if (newNode1 == NULL){
    					deleteNode = newNode1;
    					newNode2->next = NULL;
    					delete deleteNode;
    					}
    				else
    					deleteNode = newNode2;
    					newNode1->next = NULL;
    					delete deleteNode;

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    Well you shouldn't be calling new at all, you're trying to delete a node, not create three more!

    Then it is
    Code:
    while ( temp->next ) {
      prev = temp;
      temp = temp->next;
    }
    // here, temp is the node to be deleted
    // prev is the node before it (you want to set prev->next to NULL)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 06-09-2009, 02:19 AM
  2. Replies: 2
    Last Post: 02-26-2009, 10:48 PM
  3. Print function: sending a function.. through a function?
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 11-05-2008, 04:03 PM
  4. Replies: 14
    Last Post: 03-02-2008, 12:27 PM
  5. Replies: 9
    Last Post: 01-02-2007, 03:22 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21