|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | + |
| 4 | +# Definition for singly-linked list. |
| 5 | +class ListNode: |
| 6 | + def __init__(self, val=0, next=None): |
| 7 | + self.val = val |
| 8 | + self.next = next |
| 9 | + |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: |
| 13 | + if head is None or head.next is None: |
| 14 | + return head |
| 15 | + # reverse linked list |
| 16 | + prev, curr = None, head |
| 17 | + while curr: |
| 18 | + curr.next, prev, curr = prev, curr, curr.next |
| 19 | + # filter |
| 20 | + dummy = ListNode() |
| 21 | + prev, curr = dummy, prev |
| 22 | + while curr: |
| 23 | + if curr.val >= prev.val: |
| 24 | + prev.next = curr |
| 25 | + prev = curr |
| 26 | + curr = curr.next |
| 27 | + prev.next = None |
| 28 | + # reverse linked list |
| 29 | + prev, curr = None, dummy.next |
| 30 | + while curr: |
| 31 | + curr.next, prev, curr = prev, curr, curr.next |
| 32 | + return prev |
| 33 | + |
| 34 | + |
| 35 | +def main(): |
| 36 | + head = ListNode(5) |
| 37 | + head.next = ListNode(2) |
| 38 | + head.next.next = ListNode(13) |
| 39 | + head.next.next.next = ListNode(3) |
| 40 | + head.next.next.next.next = ListNode(8) |
| 41 | + head = Solution().removeNodes(head) |
| 42 | + assert head.val == 13 |
| 43 | + assert head.next.val == 8 |
| 44 | + assert head.next.next is None |
| 45 | + |
| 46 | + head = ListNode(1) |
| 47 | + head.next = ListNode(1) |
| 48 | + head.next.next = ListNode(1) |
| 49 | + head.next.next.next = ListNode(1) |
| 50 | + head = Solution().removeNodes(head) |
| 51 | + assert head.val == 1 |
| 52 | + assert head.next.val == 1 |
| 53 | + assert head.next.next.val == 1 |
| 54 | + assert head.next.next.next.val == 1 |
| 55 | + assert head.next.next.next.next is None |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + main() |
0 commit comments