patterncppMinor
Insert a Node at the Tail of a Linked List
Viewed 0 times
theinsertnodetaillistlinked
Problem
I've solved this question, but have a small question. In the while loop we check if (temp->next != NULL), why wouldn't work if we check (temp != NULL). Isn't it the same, both checks will get us to the end of the linked list? Also any code review is appreciated!
You are given the pointer to the head node of a linked list and an
integer to add to the list. Create a new node with the given integer.
Insert this node at the tail of the linked list and return the head
node. The given head pointer may be null, meaning that the initial
list is empty.
You are given the pointer to the head node of a linked list and an
integer to add to the list. Create a new node with the given integer.
Insert this node at the tail of the linked list and return the head
node. The given head pointer may be null, meaning that the initial
list is empty.
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Insert(Node *head,int data)
{
// creates a temp to hold the last node and set last's data and next
Node *last = new Node;
last->data = data;
last->next = NULL;
// if the linked list is empty then set head = last
if (head == NULL) {
head = last;
} else { // if the linked list is not empty
// creates a temp node and sets it to head
Node *temp = new Node;
temp = head;
// uses temp to find the last node
// Why do we have to use temp->next here instead of temp? wouldn't it be the same?
while (temp->next != NULL) {
temp = temp->next;
}
// appends the last node with last
temp->next = last;
}
// returns head of linked list
return head;
}Solution
Memory Leak
These lines here create a memory leak, because you allocate a node and never free it:
You don't need to allocate another node there, because you aren't actually ever using it. You can just set the
These lines here create a memory leak, because you allocate a node and never free it:
// creates a temp node and sets it to head
Node *temp = new Node;
temp = head;You don't need to allocate another node there, because you aren't actually ever using it. You can just set the
temp pointer directly to head:Node *temp = head;Code Snippets
// creates a temp node and sets it to head
Node *temp = new Node;
temp = head;Node *temp = head;Context
StackExchange Code Review Q#136077, answer score: 5
Revisions (0)
No revisions yet.