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.
The general procedure you'll want to use is:
next
pointers until you reach the node you want to insert after (call it A) next
pointer to match that of A's next
pointer 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.