Efficiently looking up a doubly linked list for a value with a pointer constraint?

I have been resolved this problem:

Suppose you are given a doubly linked list and a pointer to some element of this list. Suppose you want to find a list for some value of v that, as you know, exists somewhere. Using no pointers other than p, create the & theta; algorithm (m) -time to search for v, where m is the distance between p and node containing v. Do not modify the input list.

Does anyone have any ideas how to solve this? The only way I can think that this is destructively modifying the list.

+4
source share
2 answers

, templatetypedef , , , , " ", , , - , , .


, ? , , , , , .

, , 1 .

, , node next - , , , .

, p.prev.next ( p.prev.prev.next, ).

, , , , p.prev.next, .

Java-esque, ( , ):

if p.data == v
  return v

p = p.next
p.prev.next = p.prev.prev

while not found
  if p == v || p.prev.next == v
    p.prev.next = p                   // restore p.prev.next
    return v
  p = p.next
  p.prev.next = p.prev.prev.next.prev // set up p.prev.next from p.prev.prev.next
  p.prev.prev.next = p.prev           // restore p.prev.prev.next
+4

: , , , , ..? , ?

. , 1 + r + r 2 + r 3 +... + r n-1= (r n - 1)/(r - 1).

, !

+5

Source: https://habr.com/ru/post/1536268/


All Articles