CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2016
    Posts
    2

    Appending Node to Doubly Linked List

    Hey there, can someone please help me with this? I'm trying to append a node to a doubly linked list. It seems to crash inside the while loop after doing temp=temp->next
    Thanks a bunch!

    Code:
    void DLL::append(string ss, string name, int & count){
    	
    	Node *temp;
    	Node *newNode = new Node();
    	newNode->ssn = ss;
    	newNode->name = name;
    	newNode->next= NULL;
    	newNode->prev = NULL;
    	temp=headPtr;
    	
    	if(headPtr == NULL){
    				
    	  headPtr = newNode;	
    	  count++;	
    	  return;
    	
    	}else{
    					
    	  while(temp->next != NULL){			
    	    temp = temp->next;						
    	  }
    			
    	  newNode->prev = temp;
    	  newNode->next = NULL;
    	  temp->next = newNode;
    	  count++;	
    	}
    }
    It gathers the following:
    Code:
    20 John
    30 Mike
    40 Kate

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: Appending Node to Doubly Linked List

    How does 'it seem to crash' Have you traced through execution using the debugger? Where is headPtr set to NULL?

    Note that pointers should now be set to nullptr rather than NULL.

    Consider
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    struct Node {
    	string ssn;
    	string name;
    	Node* next;
    	Node* prev;
    };
    
    Node* headPtr = nullptr;
    
    void Append(string ss, string name, int& count)
    {
    	Node *temp = headPtr;
    	Node *newNode = new Node();
    	newNode->ssn = ss;
    	newNode->name = name;
    	newNode->next = nullptr;
    	newNode->prev = nullptr;
    
    	if (headPtr == nullptr) {
    		headPtr = newNode;
    		count++;
    		return;
    	}
    
    	while (temp->next != nullptr)
    		temp = temp->next;
    
    	newNode->prev = temp;
    	temp->next = newNode;
    	count++;
    }
    
    int main()
    {
    	int count = 0;
    	Append("20", "John", count);
    	Append("30", "Mike", count);
    	Append("40", "Kate", count);
    
    	for (Node* np = headPtr; np; np = np->next)
    		cout << np->ssn << " " << np->name << endl;
    }
    Note this example doesn't free allocated memory.
    Last edited by 2kaud; March 26th, 2016 at 04:45 PM. Reason: Code added
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Appending Node to Doubly Linked List

    I'd suggest you start by having a Node constructor that at the very least initializes your fields for you (especially the pointers). Better yet, use C++11's member initialiser.

    Anyways, a "pro tip" for doubly linked list is to make them circular, and have a "center sentinel node". This avoid having to handle null pointers at all, and eliminates most needs for any conditional testing too.

    This sample code does it. It's provided with a visitor, as it is simpler to implement than an iterator, but ideally, you'd want to provide iterators.

    Code:
    #include <iostream>
    #include <functional>
    #include <string>
    using namespace std;
    
    struct DLL {
      private:
        struct Node {
        	string ssn;
        	string name;
        	Node* next = nullptr;
        	Node* prev = nullptr;
        };
        Node sentinel;
    
      public:
        DLL() {
            sentinel.next = &sentinel;
            sentinel.prev = &sentinel;
        }
    
        void Append(string ssn, string name, int& count) {
            Node* new_guy = new Node();
            new_guy->ssn = ssn;
            new_guy->name = name;
            ConnectNode(sentinel.prev, new_guy);
            ConnectNode(new_guy, &sentinel);
            ++count;
        }
    
        void Visit(function<void(string, string)> visitor) {
            for (Node* p = sentinel.next; p != &sentinel; p = p->next) {
                visitor(p->ssn, p->name);
            }
        }
    
      private:
        void ConnectNode(Node* lhs, Node* rhs) {
            lhs->next = rhs;
            rhs->prev = lhs;
        }
    };
    
    int main()
    {
        int count = 0;
        DLL dll;
    	cout << "The list contains " << count << " entries:" << endl;
    	dll.Visit([](string ssn, string name) {cout << ssn << " " << name << endl;});
    	dll.Append("20", "John", count);
    	dll.Append("30", "Mike", count);
    	dll.Append("40", "Kate", count);
    	cout << "The list contains " << count << " entries:" << endl;
    	dll.Visit([](string ssn, string name) {cout << ssn << " " << name << endl;});
    }
    This code only contains append, but implementation for all other list primitives are just as trivial.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  4. #4
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Appending Node to Doubly Linked List

    Also, just looked at your code again: One of the main points of a doubly linked list is backwards iteration and being able to access the last element easily. You should NOT be walking your list to find the last element. That is a major fail.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured