implementing linked lists in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dynamo
    New Member
    • Apr 2007
    • 51

    implementing linked lists in c++

    hi guys
    i have this problem with the linked list algorithm,it seems every time a new link object is added it overwrites the preceding one(at least it seems so in java which the code for the algorithm is in though i want to implement it in c++)

    Code:
    public void insertFirst(int id, double dd)
    { // make new link
    Link newLink = new Link(id, dd);
    newLink.next = first; // newLink --> old first
    first = newLink; // first --> newLink
    }
    this is the code i have a problem with,specifical ly.Thanks
    p.s pls dont tell me how java handles objs.My problem is with this part of the algorithm itself(regardle ss of language).
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    As long as you make sure that you're using pointers to links and not actual links, you should be fine. Here is this written in C++ incorrectly, without pointers, so that newLink overwrites what is in first:
    Code:
    void LinkedList::insertFirst(int id, double dd) 
    { // make new link
    Link newLink(id, dd);
    newLink.next = first; // newLink --> old first
    first = newLink; // first --> newLink
    }
    But if you use pointers like this, it should work fine:
    Code:
    void LinkedList::insertFirst(int id, double dd) 
    { // make new link
    Link *newLink = new Link(id, dd);
    newLink->next = first; // newLink --> old first
    first = newLink; // first --> newLink
    }
    Hope this clarifies this a bit.

    Comment

    • fresh78
      New Member
      • Nov 2008
      • 1

      #3
      Таke a look at singly-linked list tutorial. It also has a C++ code.

      Comment

      Working...