Thread: Linked List Help

  1. #1
    Registered User
    Join Date
    Nov 2005

    Linked List Help

    My first languge was Java and now I'm trying to learn C++ because I want to program games. To practice I started implementing a simple linked list but because I'm used to a garbage collector I'm kinda unsure about deleting nodes.

    Here I'm trying to delete the first node called "head" in a linked list:
    void LinkedList::remove(int index){
    	if(index == 1){
    		Node* temp = head;
    		head = head->getNext();
    void LinkedList::freeNode(Node* nodePtr){
    	delete nodePtr; 
    Is this a good way of doing it? I tried not to put alot of code up so, let me know if you have a question.

  2. #2
    Registered User
    Join Date
    Jan 2005
    That code looks fine. If the node is not the head, then you might need to do more work, depending on your Node class.

    BTW, except for learning exercises, you should generally be using the standard C++ list class for your linked lists needs (or some other standard container) in C++.

  3. #3
    Registered User
    Join Date
    Apr 2003
    You only use delete when you've used new to allocate the memory for an object. Did you use new?

    As David mentioned, just like Java has its Vector, LinkedList, and HashMap utility classes, C++ has similar classes with iterators in the Standard Template Library(STL). The notation happens to be a little more tortured in C++. Check out "The C++ Standard Library"(Josuttis), especially chapter 5 for an overview, or check out some of the online tutorials.
    Last edited by 7stud; 11-15-2005 at 11:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Linked list program need help !!!
    By dcoll025 in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2009, 10:03 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM