correct order to insert new node?

This is a discussion on correct order to insert new node? within the C++ Programming forums, part of the General Programming Boards category; Would this be the correct order to insert a new node at P into a doubly linked list before the ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    40

    correct order to insert new node?

    Would this be the correct order to insert a new node at P into a doubly linked list before the the node pointed to cur. Thanks!

    Code:
     
    P->Next = Cur;
    P->Before = Cur->Before;
    P->Before->Next = P;
    P->Next->Before = P;

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    In theory, yes, that's fine. In practice, you'll need to do a bit more checking (this is overly cautious, assuming Cur may be null):
    Code:
    P->Next = Cur;
    if (Cur) {
      P->Before = Cur->Before;
    }
    else {
      P->Before = 0;
    }
    if (P->Before) {
      P->Before->Next = P;
    }
    if (P->Next) {
      P->Next->Before = P;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linked list question
    By brb9412 in forum C Programming
    Replies: 16
    Last Post: 01-04-2009, 04:05 PM
  2. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  3. 8 Puzzle game solver with the Best-First algoritm
    By LordMX in forum C Programming
    Replies: 17
    Last Post: 08-11-2008, 11:00 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 10:16 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

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