gunnerfunner,
1 2 3 4 5
|
node* temp = head;
do
{
temp = temp -> next;
} while (temp -> next != nullptr);
|
This dereferences a null pointer at line 4 if the list is empty, and at line 5 if the list contains exactly one item.
Your other solution doesn't meet the requirements.
vikas choudhary, here's your first solution with code tags and indentation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
Node *
Insert(Node * head, int data)
{
// Complete this method
Node *temp;
temp = head;
if (temp == '\0') {
temp = (struct Node *) malloc(sizeof(struct Node));
temp->data = data;
head = temp;
head->next = '\0';
}
else {
while (temp != '\0') {
temp = temp->next;
}
temp->data = data;
temp->next = '\0';
}
return head;
}
|
The problem here is that line 18 derefences a null pointer.
Regarding your second attempt, gunnerfunner pointed out one bug (deleting s). In addition, that will fail if there is exactly one item in the list because line 16 (
temp = temp->next
) will assign a null pointer to temp and the next line will dereference it.
Here is a modified version of your first attempt that works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
Node *
Insert(Node * head, int data)
{
// Create the new node just once.
Node *newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
// Point temp to the last node
Node *temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
// Now append the newNode
temp->next = newNode;
}
return head;
}
|
But this is still a crappy way to insert into a linked list because it requires that you always call Insert with
head = Insert(head, somevalue);
. It makes much more sense to pass a reference to the head pointer (
void Insert Node* &head, int data)
).
If Insert() had that prototype then the code could be written without special cases by using a pointer-to-pointer. This points to either
head
, or the
next
member that points to the current node:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void
Insert(Node * &head, int data)
{
// Create the new node just once.
Node *newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
Node **headOrNext = &head;
while (*headOrNext) {
headOrNext = &(*headOrNext)->next;
}
*headOrNext = newNode;
}
|
By the way, the same method works great when deleting nodes.