Swap with the stack

The stack gives values back in the opposite order from the order in which they went in. This is useful for swapping two values.

What to build

Read two keys and print them in the opposite order, using only PUSH and POP to swap them.

Requirements

  • Push both keys.
  • Pop and print them.
  • Do not use XCHG or a third register to hold a key.

Input

Two characters, then Enter.

Output

The same two characters, swapped.

Constraints

The characters are letters or digits.

Example

Input:

ab

Output:

ba

Why it works

A PUSH puts the word on top of the stack and a POP takes the top word off, so the key pushed last is the first to come back. PUSH needs a 16-bit register, so the whole of AX is pushed, with the key in AL. POP DX then puts the key in DL, ready to be printed.

Examples

Example 1 · Input
ab
Expected output
ba
Example 2 · Input
12
Expected output
21

Hints

Hint 1

Read the two keys and PUSH each one in turn: PUSH AX puts a whole word on the stack.

Hint 2

The last one pushed is the first popped, so two POP DX instructions give the second key, then the first.

Hint 3

Print DL after each POP with AH = 2. Do not use XCHG.

Solution

Show one correct solution (try it yourself first)
; Swap with the stack
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
    MOV AH, 1
    INT 21H
    PUSH AX             ; the first key
    INT 21H
    PUSH AX             ; the second key
    POP DX              ; the second comes off first
    MOV AH, 2
    INT 21H
    POP DX
    INT 21H
    MOV AH, 4CH
    INT 21H
MAIN ENDP
END MAIN

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: The stack →