Can anyone help me in this question?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • S2510
    New Member
    • Jan 2016
    • 4

    Can anyone help me in this question?

    Given a linked list class defined as follows:

    Code:
    class NumberList 
    {     
    private:
         struct Node       
    {          
           double value;          
           struct Node *next;       
    };       
          ListNode *head;  //points to the first node        public:          
           NumberList(); 
    }
    Write a member function remove(int i) to remove the element at position i. If i is equal to or greater than the length of the list (or less than 0) then the list should remain unchanged.
    Last edited by zmbd; Jan 7 '16, 03:40 AM.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    To remove an element, the next* of the element preceding the element to be deleted must be set to the node pointer of the element being deleted.

    It will help when you traverse the list looking for the element to be deleted to remember what the previous node was because you will need that info should you remove an element.

    Comment

    • S2510
      New Member
      • Jan 2016
      • 4

      #3
      I didn't get you! Can you please explain me?

      Comment

      • zmbd
        Recognized Expert Moderator Expert
        • Mar 2012
        • 5501

        #4
        S2510: Homework question?

        Comment

        • S2510
          New Member
          • Jan 2016
          • 4

          #5
          Not a homework question. Preparing for a programming exam. Got stuck in this question. Thanks

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            OK. Take 3 nodes A B C.

            So A.next = &B and B.next = &C and C.next = 0 (because it's the end).

            To delete B you must set A.next = B.next.

            When you locate B to remove it, you will need the address of A since you need to change the value in A.next.

            However, there is no previous node in B. So you will need remember what the previous node to B was as you search for B.

            Comment

            • S2510
              New Member
              • Jan 2016
              • 4

              #7
              Thank you!!
              Got an idea!!
              Will try to write a program and verify!!

              Comment

              Working...