Problem Session 1

69 阅读1分钟

Problen session:

1-2:

Given a data structure D supporting the four first/last sequence operations:

D.insert first(x), D.delete first(), D.insert last(x), D.delete last(),

each in O(1) time, describe algorithms to implement the following higher-level operations in terms of the lower-level operations. Recall that delete operations return the deleted item. (a)

Code:

def swap_ends(D):
    x_first = D.delete_first()
    x_last = D.delete_last()
    D.insert_first(x_last)
    D.insert_last(x_first)

(b):shift left(D, k): Move the first k items in order to the end of the sequence n D in O(k) time. (After, the kth item should be last and the (k + 1)st item should be first.)

def shift(D, k):
    if (k <= 0) or (k >= len(D)):
        return
    x = D.delete_first()
    D.insert_last(x)
    shift(D, k - 1)

1-4:

问题描述:

我们要将一个长度为2n的链表,分为两个长度为n的部分,但同时要保证后半段链表的“公平性”,因此便有了关键代码

x_n = x.next
x.next= x_p
x_p, x = x , x_n

完整代码:

def reorder(L):
    n = len(L) // 2
    a = L.head
    for _ in range(n - 1):
        a = a.next
    b = a.next
    x_p, x, x_n = a, b
    for _ in range(n):
        x_n = x.next  # 用于记录x.next,因为我们马上就要更改现有的x_next了
        x.next = x_p  # 更改x.next,指向x的前一个元素
        x_p, x = x, x_n  # 按原有列表进行迭代
    c = x_p
    a.next = c
    b.next = None

    return