Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2017/imperative-programming-resit/4/c/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 4 c Solution by
Codex 0 2026-10-31
Use a helper whose first argument is a private result list. It adds a coefficient to an existing power, deleting a cancellation, or allocates a new node:
accumulate(VAR r: poly; c: T; e: INTEGER):
if c == 0: return
p = r; prev = NIL
while p != NIL and p.power != e:
prev = p; p = p.next
if p == NIL:
q = new term(c,e,r)
r = q
else:
p.coeff = p.coeff+c
if p.coeff == 0:
if prev == NIL: r = p.next
else: prev.next = p.next
addPoly(x,y):
r = NIL
p = x
while p != NIL:
accumulate(r,p.coeff,p.power)
p = p.next
p = y
while p != NIL:
accumulate(r,p.coeff,p.power)
p = p.next
return rHere
VAR applies to the list variable r; coefficients and powers are value arguments. The helper preserves one node per power and excludes zero coefficients. After each loop iteration, the result represents exactly the processed input terms. Every result node is fresh, so neither input's nodes or links are changed, even if the two inputs alias or share tails. For unsorted inputs of lengths , a simple worst-case bound is for these repeated scans. New to topics? Read the docs here!