Problem:
Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1

Solution in OCaml (judge verdict: Accepted)

module DoublyLinkedList = struct
  type t = {
    mutable data : int;
    mutable next : t;
    mutable prev : t;
  }

  let make () =
    let rec head = { data = 0; next = head; prev = head } in
    head

  let insert data head =
    let x = { data = data; next = head.next; prev = head } in
    head.next.prev <- x;
    head.next <- x

  let delete x =
    x.next.prev <- x.prev;
    x.prev.next <- x.next

  let delete_first head = delete head.next

  let delete_last head = delete head.prev

  let delete_node data head =
    let rec doit ite =
      if ite == head then None
      else if ite.data = data then Some ite
      else doit ite.next
    in
    match doit head.next with
    | None -> ()
    | Some ite -> delete ite

  let iteri head ~f =
    let rec doit i ite =
      if ite == head then ()
      else (f i ite.data; doit (i + 1) ite.next)
    in
    doit 0 head.next
end

module L = DoublyLinkedList

let () =
  let n = read_int () in
  let head = L.make () in
  let rec read i =
    if i >= n then ()
    else begin
      match Str.split (Str.regexp " ") (read_line ()) with
      | ["insert"; n] -> (L.insert (int_of_string n) head; read (i + 1))
      | ["delete"; n] -> (L.delete_node (int_of_string n) head; read (i + 1))
      | ["deleteFirst"] -> (L.delete_first head; read (i + 1))
      | ["deleteLast"] -> (L.delete_last head; read (i + 1))
      | _ -> exit 1
    end
  in
  read 0;
  L.iteri head ~f:(fun i n -> Printf.printf (if i = 0 then "%d" else " %d") n);
  print_newline ()