1
class List {
  ListNode *head;
  ListNode *prev;
};

class ListNode {
  int data;
  ListNode *next;
  friend class List;
  ListNode(int d, ListNode *n) : data(d), next(NULL) {}
  void insertM(int d) {
    ListNode *ptr, *temp, *curr;
    ptr = head;
    while (ptr->data < d) {
      prev = ptr;
      ptr = ptr->next;
    } // end while
    temp = prev->next;
    curr = new ListNode(d, ptr);
    curr->next = prev->next; // or temp->next
    prev->next = curr;
    ;
  }
};

List mylist;

In this function, I'm trying to add a node in the middle of linked list. Other functions add items to the back and front just fine. When I add in the middle of the list, my prev->next links to curr just fine, but curr->next points to NULL.

I have been trying to make this program work for past 1.5 hours. I'll appreciate your help. This is homework.

1 Answer 1

1

The general procedure you'll want to use is:

  1. surf down the next pointers until you reach the node you want to insert after (call it A)
  2. change your inserted node (B)'s next pointer to match that of A's next pointer
  3. change A's next pointer to point to B

It looks from your code that you're trying to maintain a sorted list of integers. This being homework you probably won't get a code snippet, but from glancing at your code, I have to ask why you take a next parameter in your node constructor, but then set the next value to null. Without seeing the rest of your code I can't say for sure, but I'd change next(NULL) on line 9 to be next(n), and then remove the curr->next line near the bottom

Sign up to request clarification or add additional context in comments.

1 Comment

Now my code is working. It has been working but then I changed next(n) to next(NULL) for some reason. Now it's working fine. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.