recategorized by
784 views
1 votes
1 votes

Let $L$ be a singly-linked list $X$ and $Y$ be additional pointer variables such that $X$ points to the first element of $L$ and $Y$ points to the last element of $L$. Which of the following operations cannot be done in time that is bound above by a constant?

  1. Delete the first element of $L$.
  2. Delete the last element of $L$.
  3. Add an element after the last element of $L$.
  4. Add an element before the first element of $L$.
  5. Interchange the first two elements of $L$.
recategorized by

1 Answer

1 votes
1 votes
$(A)$
$ Y \to next = Y \to next \to next$
$X = Y \to next$

$(C)$
$temp = \text{(int *)(malloc(sizeof(int)))}$
$temp \to data = val$
$temp \to next = X$
$Y \to next = temp$
$Y = temp$

$(D)$
$temp = \text{(int *)(malloc(sizeof(int)))}$
$temp \to data = val$
$temp \to next = X$
$Y \to next = temp$
$X = temp$

$(E)$
$temp = X \to next \to data$
$X \to next \to data = X \to data$
$X \to data = temp$

 

Now, let's look at the Part $(B)$
Let’s copy the data of $X$ in $Y$ and then delete $X$.

$Y \to data = X \to data$
$Y \to next = X \to next$
$X = Y$

Now we need to point $Y$ to the previous node of the newly set $X$. How do we do that in constant time?
For that, we need to iterate starting from $X$ to the last node which will take $O(n)$ time where $n$ is the number of nodes in the list.

So, the answer should be $(B)$
Answer:

Related questions

2 votes
2 votes
1 answer
3
soujanyareddy13 asked Mar 25, 2021
493 views
Consider the following two languages.$\begin{array}{rcl} \text{PRIME} & = & \{ 1^{n} \mid n \text{ is a prime number} \}, \\ \text{FACTOR} & = & \{ 1^{n}0 1^{a} 01^{b} ...