Switch successive pairs using an auxiliary queue. Args: stack: A list representing a stack (bottom to top). Returns: The stack with successive pairs swapped. Examples: >>> second_switch_pairs([3, 8, 17, 9, 1, 10]) [8, 3, 9, 17, 10, 1]
(stack: list[int])
| 47 | |
| 48 | |
| 49 | def second_switch_pairs(stack: list[int]) -> list[int]: |
| 50 | """Switch successive pairs using an auxiliary queue. |
| 51 | |
| 52 | Args: |
| 53 | stack: A list representing a stack (bottom to top). |
| 54 | |
| 55 | Returns: |
| 56 | The stack with successive pairs swapped. |
| 57 | |
| 58 | Examples: |
| 59 | >>> second_switch_pairs([3, 8, 17, 9, 1, 10]) |
| 60 | [8, 3, 9, 17, 10, 1] |
| 61 | """ |
| 62 | queue: collections.deque[int] = collections.deque() |
| 63 | for _ in range(len(stack)): |
| 64 | queue.append(stack.pop()) |
| 65 | for _ in range(len(queue)): |
| 66 | stack.append(queue.pop()) |
| 67 | for _ in range(len(stack)): |
| 68 | queue.append(stack.pop()) |
| 69 | for _ in range(len(queue)): |
| 70 | if len(queue) == 0: |
| 71 | break |
| 72 | first = queue.pop() |
| 73 | if len(queue) == 0: |
| 74 | stack.append(first) |
| 75 | break |
| 76 | second = queue.pop() |
| 77 | stack.append(second) |
| 78 | stack.append(first) |
| 79 | |
| 80 | return stack |