Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node for the stack.
DSA C
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = [1];
node->next = NULL;
return node;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning NULL or 0 instead of the input data.
Assigning the node pointer itself.
✗ Incorrect
The new node's data field should be set to the input parameter 'data'.
2fill in blank
mediumComplete the code to check if the stack is empty.
DSA C
int isEmpty(struct Node* top) {
return [1] == NULL;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking top->next instead of top.
Comparing data field to NULL.
✗ Incorrect
The stack is empty if the top pointer is NULL.
3fill in blank
hardFix the error in the push function to correctly add a new node on top of the stack.
DSA C
void push(struct Node** top_ref, int data) {
struct Node* node = newNode(data);
node->next = [1];
*top_ref = node;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using top_ref instead of *top_ref.
Using top_ref->next which is invalid pointer access.
✗ Incorrect
The new node's next should point to the current top node, which is *top_ref.
4fill in blank
hardFill both blanks to correctly pop the top element from the stack and return its data.
DSA C
int pop(struct Node** top_ref) {
if (isEmpty(*top_ref))
return -1;
struct Node* temp = [1];
int popped = temp->data;
*top_ref = [2];
free(temp);
return popped;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning temp to top_ref instead of *top_ref.
Not updating *top_ref to the next node.
✗ Incorrect
temp should point to the current top node (*top_ref), and top_ref should be updated to the next node (*top_ref)->next.
5fill in blank
hardFill in the blank to implement a peek function that returns the top element's data without removing it.
DSA C
int peek(struct Node* top) {
if (top == NULL)
return -1;
return [1];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning top pointer instead of its data.
Returning top->next which is the next node, not the data.
✗ Incorrect
The peek function returns the data of the top node without modifying the stack.
