|
1 |
| -from linked_list_utils import * |
| 1 | +from chapter_2.linked_list_utils import Node, llol |
2 | 2 |
|
3 | 3 |
|
4 |
| -def k_to_last(k: int, h: Node): |
5 |
| - ldr = h |
6 |
| - folw = h |
7 |
| - d = -1 |
| 4 | +def remove_dups_ll(head: Node): |
| 5 | + seen = set() |
| 6 | + prev = None |
| 7 | + while head: |
| 8 | + if head.val in seen: |
| 9 | + prev.next = head.next |
| 10 | + else: |
| 11 | + seen.add(head.val) |
| 12 | + prev = head |
| 13 | + head = head.next |
8 | 14 |
|
9 |
| - while ldr: |
10 |
| - print(f"Ldr is {ldr} and folw {folw}") |
11 |
| - d += 1 |
12 |
| - if d > k: |
13 |
| - folw = folw.next |
14 |
| - ldr = ldr.next |
15 | 15 |
|
16 |
| - if d<k: |
17 |
| - raise Exception(f"Input too short for distance {d}") |
18 |
| - |
19 |
| - return folw.val |
| 16 | +def remove_dups_nobuf(h: Node): |
| 17 | + rc = h |
| 18 | + while rc: |
| 19 | + target = rc.val |
| 20 | + prev = rc |
| 21 | + restp = rc.next |
| 22 | + while restp: |
| 23 | + if restp.val == target: |
| 24 | + prev.next = restp.next |
| 25 | + else: |
| 26 | + prev = restp |
| 27 | + restp = restp.next |
| 28 | + rc = rc.next |
20 | 29 |
|
21 | 30 |
|
22 | 31 | if __name__ == "__main__":
|
23 |
| - ex1 = link_list_of_list([1, 2, 3, 4, 5, 6, 7]) |
24 |
| - d = 5 |
25 |
| - print(ex1) |
26 |
| - print(k_to_last(d, ex1)) |
| 32 | + exs = [[1, 2, 3, 4, 5], |
| 33 | + [11, 2, 3, 4, 5, 6, 11], |
| 34 | + [11, 2, 3, 4, 5, 6, 11, 11, 11, 23], |
| 35 | + [0], |
| 36 | + [0, 0], |
| 37 | + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 3, 1]] |
| 38 | + |
| 39 | + for ex in exs: |
| 40 | + r1 = llol(ex) |
| 41 | + r2 = llol(ex) |
| 42 | + remove_dups_nobuf(r1) |
| 43 | + remove_dups_nobuf(r2) |
| 44 | + print(f"For ex {ex} for ans 1: {r1}") |
| 45 | + print(f"For ex {ex} for ans 2: {r2}") |
| 46 | + print("-"*50) |
0 commit comments