• retagged by
265 views
7 7 votes

Consider the following C function intended to delete the last node of a singly linked list:

void removeLast(struct Node *head) {
    struct Node *p = head;
    struct Node *q = p->next;

    while (q->next != NULL) {
        p = q;
        q = q->next;
    }

    p->next = NULL;
    free(q);
}

For which linked lists does this function work correctly?

  1. No linked lists
     
  2. All non-empty linked lists
     
  3. All linked lists with more than one node
     
  4. Empty list and all linked lists with more than one node
     
  5. All linked lists

4 Answers

1 1 vote

If the list is empty, $\texttt{head == NULL}$, so $\texttt{p->next}$ causes invalid access.

If the list has one node, then $\texttt{q = p->next}$ becomes $\texttt{NULL}$, so $\texttt{q->next}$ causes invalid access.

For lists with more than one node, $\texttt{p}$ reaches the second-last node and $\texttt{q}$ reaches the last node. 

Then $\texttt{p->next = NULL}$ removes the last node correctly.

Answer : C

0 0 votes
Answer: C. All linked lists with more than one node, because empty list and list with one node causes invalid access, but more than one node causes no problems.
Answer:
Position:
Show:

Related questions

9 9 votes
3 3 answers
271
271 views
GO Classes asked Jul 4
271 views
Consider the problem of finding the middle node in a list $l$ of size $n$, given that $n$ is odd. Count the number of accesses to positions of list $l$ needed to find the...
3 3 votes
3 3 answers
248
248 views
GO Classes asked Jul 4
248 views
Consider the following singly linked list:$\texttt{'B' - 'A' - 'S' - 'E' - NULL}$The pointer $\texttt{head}$ points to the first node containing $\texttt{'B'}$.What chara...
7 7 votes
2 2 answers
259
259 views
GO Classes asked Jul 4
259 views
A singly linked list maintains two pointers:struct Node *front; // points to first node struct Node *rear; // points to last nodeWhich operation would be inefficient when...
6 6 votes
3 3 answers
260
260 views
GO Classes asked Jul 4
260 views
Consider the following structure:struct Node { int data; struct Node *next; };A function should insert a new node containing value $\texttt{x}$ at the beginning of a sing...