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

Template in C
-->


Sample input:
7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5


Sample output:
6 1 2

Submission status: Accepted

Solution code:
from collections import deque
import sys

stack = deque()

def linked_list(stack,command,x=None):

    if command == "insert":#stackの左端にxを追加
        stack.appendleft(x)

    elif command == "delete":#左端から数えて最初のxを削除
        try:
            stack.remove(x)
        except:
            pass

    elif command == "deleteFirst":#左端の要素を削除
        stack.popleft()

    elif command == "deleteLast":#右端の要素を削除
        stack.pop() 


N = int(input())
#lst = [l.split() for l in sys.stdin.readlines()]
#print(lst)
for i in range(N):

    #print(i)
    input_command = input()


    if input_command == "deleteFirst":#左端の要素を削除
        stack.popleft()

    elif input_command == "deleteLast":#右端の要素を削除
        stack.pop() 

    else:
        command,x = input_command.split()
        if command == "insert":#stackの左端にxを追加
            stack.appendleft(x)

        elif command == "delete":#左端から数えて最初のxを削除
            try:
                stack.remove(x)
            except:
                pass

print(" ".join(map(str,stack)))

Submission status: Accepted

Solution code:
from collections import deque


def main():
    doubly_liked_list = deque()
    n = int(input())
    for i in range(n):
        command = input()
        if command == 'deleteFirst':
            doubly_liked_list.popleft()
        elif command == 'deleteLast':
            doubly_liked_list.pop()
        else:
            command = command.split()
            if command[0] == 'insert':
                doubly_liked_list.appendleft(int(command[1]))
            elif command[0] == 'delete':
                try:
                    doubly_liked_list.remove(int(command[1]))
                except:
                    pass
    print(*doubly_liked_list)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
ans = deque()

while N > 0:
    N -= 1

    tmp = input().split()

    if tmp[0] == "delete":
        # for文だとTLEになる
        # for i in range(len(ans)):
        #     if ans[i] == tmp[1]:
        #         ans.pop(i)
        #         break

        try:
            ans.remove(tmp[1])
        except:
            pass

    elif tmp[0] == "deleteFirst":
        ans.popleft()

    elif tmp[0] == "deleteLast":
        ans.pop()

    else:
        ans.appendleft(tmp[1])

print(*ans)

Submission status: Accepted

Solution code:
from collections import deque


def print_list(que):
    for i, q in enumerate(que):
        if i != len(que)-1:
            print(q, end=' ')
        else:
            print(q)


def main():
    List = deque()
    n = int(input())
    for i in range(n):
        order = input().split()
        if order[0] == "insert":
            List.appendleft(order[1])
        elif order[0] == "delete":
            try:
                List.remove(order[1])
            except ValueError:
                pass
        elif order[0] == "deleteFirst":
            List.popleft()
        elif order[0] == "deleteLast":
            List.pop()
    print_list(List)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.nil = Node(None) # 番兵
        self.nil.prev = self.nil
        self.nil.next = self.nil # prevもnextも番兵に接続

    def insert(self, key):
        new = Node(key)
        new.next = self.nil.next   # 新しいNodeの後ろをもともと番兵の後ろにあったNodeに変更
        self.nil.next.prev = new   # もともと番兵の次にあったNodeの前を新しいNodeに変更
        self.nil.next = new        # 番兵の後ろを新しいNodeに変更
        new.prev = self.nil        # 新しいNodeの前をnilに指定

    def listSearch(self, key):
        cur = self.nil.next
        while cur != self.nil and cur.key != key:
            cur = cur.next
        return cur

    def deleteNode(self, t):
        if t == self.nil:
            return
        t.prev.next = t.next
        t.next.prev = t.prev

    def deleteFirst(self):
        self.deleteNode(self.nil.next)

    def deleteLast(self):
        self.deleteNode(self.nil.prev)

    def deleteKey(self, key):
        self.deleteNode(self.listSearch(key))


if __name__ == '__main__':
    import sys
    input = sys.stdin.readline  # 入力の高速化

    n = int(input())

    dll = DoublyLinkedList()

    for _ in range(n):
        '''
        以下のようにcomとkeyに分けるとTimeLimitExceededになるので、comだけで処理しました
        (別のいい方法があれば教えて欲しいです)
        com, *key = input().split()
        この場合keyがリストになるので、com[7:]をkey[0]で置き換える必要があります。
        (xがない命令ではkey=[]となるだけ)
        '''
        com = input().rstrip()
        # 以下、本と順番など多少異なります
        if com[0] == 'i':
            dll.insert(com[7:])
        elif com[6] == 'F':
            dll.deleteFirst()
        elif com[6] == 'L':
            dll.deleteLast()
        else:
            dll.deleteKey(com[7:])

    cur = dll.nil.next
    ans = []
    while cur != dll.nil:
        ans.append(cur.key)
        cur = cur.next

    print(' '.join(ans))

Submission status: Accepted

Solution code:
from collections import deque
import sys

input()
lst = deque()

for s in sys.stdin:
    if s[0] == 'i':
        lst.appendleft(s[7:-1])

    else:
        a = s[6]
        if a == ' ':
            try:
                lst.remove(s[7:-1])
            except:
                pass

        elif a == 'F':
                lst.popleft()

        else:
            lst.pop()

print(*lst)

Submission status: Accepted

Solution code:
from collections import deque
from sys import stdin
n = int(input())
L = deque()
for _ in range(n):
    com = list(map(str, stdin.readline().split()))
    if com[0] == 'insert':
        i = int(com[1])
        L.appendleft(i)
    elif com[0] == 'delete':
        i = int(com[1])
        try:
            L.remove(i)
        except ValueError:
            continue
    elif com[0] == 'deleteFirst':
        L.popleft()
    elif com[0] == 'deleteLast':
        L.pop()
for i in range(len(L)):
    if i == len(L) - 1:
        print(L[i])
    else:
        print(L[i], end=' ')

Submission status: Accepted

Solution code:
from collections import deque
num=int(input())
a=deque()
for i in range(num):
    tmp=input().split()
    if tmp[0]=="insert":
        a.appendleft(tmp[1])
    if tmp[0]=="delete":
        if tmp[1] in a:
            a.remove(tmp[1])
    if tmp[0]=="deleteFirst":
        a.popleft()
    if tmp[0]=="deleteLast":
        a.pop()
print(" ".join(a))

Submission status: Accepted

Solution code:
from collections import deque

LIST = deque()

num_command = int(input())

for loop in range(num_command):

    input_command = input()

    if input_command == 'deleteFirst':
        LIST.popleft()
    elif input_command == 'deleteLast':
        LIST.pop()
    else:
        com,num = input_command.split()

        if com == 'insert':
            LIST.appendleft(num)
        elif com == 'delete':
            try:
                LIST.remove(num)
            except:
                pass

print(' '.join(LIST))

Submission status: Accepted

Solution code:
class Node(object):
    def __init__(self, num, prv = None, nxt = None): 
        self.num = num
        self.prv = prv
        self.nxt = nxt
        
class DoublyLinkedList(object):
    def __init__(self):
        self.start = self.last = None 
 
    def insert(self, num):
        new_elem = Node(num)
        
        if self.start is None: 
            self.start = self.last = new_elem
        else:
            new_elem.nxt = self.start
            self.start.prv = new_elem
            self.start = new_elem
 
    def delete_num(self, target): 
        it = self.start
        
        while it is not None:
            if it.num == target:
                if it.prv is None and it.nxt is None: 
                    self.start = self.last = None
                else:
                    if it.prv is not None: 
                        it.prv.nxt = it.nxt
                    else: # [target, a, b,]
                        self.start = self.start.nxt
 
                    if it.nxt is not None: 
                        it.nxt.prv = it.prv
                    else: 
                        self.last = self.last.prv
                break
            it = it.nxt
 
    def delete_start(self): 
        if self.start is self.last: 
            self.start = self.last = None
        else:
            self.start.nxt.prv = None
            self.start = self.start.nxt
 
    def delete_last(self):
        if self.start is self.last:
            self.start = self.last = None
        else:
            self.last.prv.nxt = None
            self.last = self.last.prv
 
    def get_content(self):
        ret = [] 
        it = self.start
 
        while it is not None:
            ret.append(it.num)
            it = it.nxt
 
        return ' '.join(ret)

def _main():
    from sys import stdin
    n = int(input())
    lst = DoublyLinkedList()
    for _ in range(n):
        cmd = stdin.readline().strip().split()
        if cmd[0] == 'insert':
            lst.insert(cmd[1])
        elif cmd[0] == 'delete':
            lst.delete_num(cmd[1])
        elif cmd[0] == 'deleteFirst':
            lst.delete_start()
        elif cmd[0] == 'deleteLast':
            lst.delete_last()
 
    print(lst.get_content())
    
if __name__ == '__main__': 
    _main()

Submission status: Accepted

Solution code:
from collections import deque
que = deque()

n = int(input())
for _ in range(n):
    command = input()
    if command == 'deleteFirst':
        que.popleft()
    elif command == 'deleteLast':
        que.pop()
    else:
        x, y = command.split()
        if x == 'insert':
            que.appendleft(int(y))
        elif int(y) in que:
            que.remove(int(y))

print(' '.join(map(str, que)))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
d = deque()
for i in range(n):
    x = input().split()

    if x[0] == "insert":
        d.appendleft(x[1])
    elif x[0] == "delete":
        if x[1] in d:
            d.remove(x[1])
    elif x[0] == "deleteFirst":
        d.popleft()
    elif x[0] == "deleteLast":
        d.pop()

print(*d)

Submission status: Accepted

Solution code:
from collections import deque

dq = deque()

n = int(input())

for _ in range(n):
    command = input()
    if command[:6] == 'insert':
        dq.appendleft(command[7:])
    elif command[:10] == 'deleteLast':
        dq.pop()
    elif command[:11] == 'deleteFirst':
        dq.popleft()
    elif command[:6] == 'delete':
        if (command[7:]) in dq:
            dq.remove(command[7:])
print(" ".join(dq))

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque
import copy

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    que = deque()

    for n in range(N):
        cmd = sl()
        if cmd[0] == 'insert':
            que.appendleft(cmd[1])
        elif cmd[0] == 'delete' and cmd[1] in que:
            que.remove(cmd[1])
        elif cmd[0] == 'deleteFirst' and len(que) > 0:
            que.popleft()
        elif cmd[0] == 'deleteLast' and len(que) > 0:
            que.pop()
    print(*que)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque
input = stdin.readline

nodelist = deque()
N = int(input())
for i in range(N):
    command = input().split()
    if command[0] == 'insert':
        nodelist.appendleft(command[1])
    elif command[0] == 'delete':
        try:
            nodelist.remove(command[1])
        except:
            continue
    elif command[0] == 'deleteFirst':
        nodelist.popleft()
    else:
        nodelist.pop()
print(*nodelist)

Submission status: Accepted

Solution code:
from collections import deque
num = deque()
n = int(input())
for i in range(n):
    com = input().split()
    if com[0] == "deleteFirst":
        num.popleft()
    elif com[0] == "deleteLast":
        num.pop()
    elif com[0] == "insert":
        num.insert(0, com[1])
    elif com[0] == "delete":
        if num.count(com[1]):
            num.remove(com[1])
print(" ".join(num))

Submission status: Accepted

Solution code:
from collections import deque
d = deque()
n = int(input())
for i in range(n):
    s = input()
    if s == "deleteFirst":
        d.popleft()
    elif s == "deleteLast":
        d.pop()
    elif s[:6] == "insert":
        d.appendleft(int(s[7:]))
    else:
        delkey = int(s[7:])
        if delkey in d:
            d.remove(delkey)

print(" ".join(map(str,d)))

Submission status: Accepted

Solution code:
import sys
from collections import deque


input = sys.stdin.readline

n = int(input())
orders = []
for i in range(n):
    orders.append(input().strip())

#orders = ["insert 5","insert 2","insert 3","insert 1","delete 3","insert 6","delete 5"]
#orders = ["insert 5","insert 2","insert 3","insert 1","delete 3","insert 6","delete 5","deleteFirst","deleteLast"]

data = deque()
for d in orders:
    if " " in d:
        order, value = d.split(" ")
    else:
        order = d

    if order == "insert":
        data.appendleft(value)
    elif order == "delete":
        try:
            data.remove(value)
        except ValueError:
            pass
    elif order == "deleteFirst":
        data.popleft()
    elif order == "deleteLast":
        data.pop()
    else:
        print('Unknown order')

# print result
print(" ".join(data))

Submission status: Accepted

Solution code:
#-*-coding:utf-8-*-

from collections import deque
import sys
input=sys.stdin.readline

def main():
    commands=[]
    number = int(input())
    commands=list(input().split() for _ in range(number))
    q=deque()
    for command in commands:
        if command[0] == "insert":
            q.appendleft(command[1])
        elif command[0] == "delete":
            if command[1] in q:
                q.remove(command[1])
            else:
                continue
        elif command[0] == "deleteFirst":
            q.popleft()
        elif command[0] == "deleteLast":
            q.pop()
    print(*q)
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

class Node:
    def __init__(self, val):
        self.val  = val
        self.prev = None
        self.next = None

class DoublyLinkedList:
    def __init__(self):
        self.sentinel = Node(None)
        self.sentinel.prev = self.sentinel
        self.sentinel.next = self.sentinel

    def insert(self, val):
        node = Node(val)
        node.prev = self.sentinel
        node.next = self.sentinel.next
        self.sentinel.next.prev = node
        self.sentinel.next = node

    def delete(self, val):
        self.delete_node(self.search(val))

    def deleteFirst(self):
        self.delete_node(self.sentinel.next)

    def deleteLast(self):
        self.delete_node(self.sentinel.prev)

    def search(self, val):
        cursor = self.sentinel.next
        while cursor != self.sentinel and cursor.val != val:
            cursor = cursor.next
        return cursor

    def delete_node(self, node):
        if node == self.sentinel:
            return
        node.prev.next = node.next
        node.next.prev = node.prev

n = int(input())
linked_list = DoublyLinkedList()
for index in range(n):
    command = input().rstrip()
    if command[0] == 'i':
        linked_list.insert(command[7:])
    elif command[6] == 'F':
        linked_list.deleteFirst()
    elif command[6] == 'L':
        linked_list.deleteLast()
    else:
        linked_list.delete(command[7:])

node = linked_list.sentinel.next
output = []
while node != linked_list.sentinel:
    output.append(node.val)
    node = node.next
print(" ".join(map(str, output)))

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
queue = deque()

for _ in range(n):
    tmp = input().split()
    cmd = tmp[0]
    if cmd == 'insert':
        queue.appendleft(tmp[1])
    elif cmd == 'delete':
        try:
            queue.remove(tmp[1])
        except ValueError:
            pass
    elif cmd == 'deleteFirst':
        queue.popleft()
    else:
        queue.pop()

print(' '.join(queue))

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

n = int(input())
l = deque()

for _ in range(n):
    op = input().strip().split()
    if op[0] == "insert":
        l.appendleft(op[1])
    elif op[0] == "delete":
        if op[1] in l:
            l.remove(op[1])
    elif op[0] == "deleteFirst":
        l.popleft()
    elif op[0] == "deleteLast":
        l.pop()
print(" ".join(l))

Submission status: Accepted

Solution code:
from collections import deque

if __name__ == '__main__':
    l = deque()
    n = int(input())
    for _ in range(n):
        m = input().split()
        if m[0] == 'insert':
            l.appendleft(m[1])
        elif m[0] == 'delete':
            try:
                l.remove(m[1])
            except:
                pass
        elif m[0] == 'deleteFirst':
            l.popleft()
        elif m[0] == 'deleteLast':
            l.pop()
    print(' '.join(map(str, l)))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())

q = deque()
for i in range(n) :
    command = input().split()
    if command[0] == 'insert' :
        q.appendleft(command[1])
    elif command[0] == 'delete' :
        try :
            q.remove(command[1])
        except ValueError :
            pass
    elif command[0] == 'deleteFirst' :
        q.popleft()
    elif command[0] == 'deleteLast' :
        q.pop()
print(*q)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())

x_list=deque()

for i in range(N):
    a = input().split()
    if a[0] == "insert":
        x_list.appendleft(a[1])
    elif a[0] == "delete":
        try:
            x_list.remove(a[1])
        except:
            pass
    elif a[0] == "deleteFirst":
        x_list.popleft()
    else:
        x_list.pop()

print(*x_list)

Submission status: Accepted

Solution code:
from collections import deque


deq = deque()
n = int(input())
for _ in range(n):
    operation = input()
    if operation == "deleteFirst":
        deq.popleft()
    elif operation == "deleteLast":
        deq.pop()
    
    else:
        command, value = operation.split()
        if command == "insert":
            deq.appendleft(int(value))
        elif command == "delete":
            try:
                deq.remove(int(value))
            except ValueError:
                pass

print(*deq)

Submission status: Accepted

Solution code:
from collections import deque

N = int(input().rstrip())

dll = deque()

for n in range(N):
    command = input().rstrip()
    if command.endswith(("First", "Last")):
        if command == "deleteFirst":
            dll.popleft()
        else:
            dll.pop()
    else:
        command, x = command.split(" ")
        if command =="insert":
            dll.appendleft(x)
        else:
            try:
                dll.remove(x)
            except Exception as e:
                pass
            
print(" ".join(dll))

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
d = deque()

for i in range(n):
    c = input()
    if ' ' in c:
        c, num = c.split()
        if c == 'insert':
            d.appendleft(num)
        elif c == 'delete' and num in d:
            d.remove(num)
    else:
        if c == 'deleteFirst' and d:
            d.popleft()
        elif c == 'deleteLast' and d:
            d.pop()

print(' '.join(d))

Submission status: Accepted

Solution code:
import sys


class Node:
    def __init__(self, x):
        self.x = x

    def set_prev(self, prev):
        self.prev = prev

    def set_next(self, next):
        self.next = next


class DoublelyLinkedList:
    def __init__(self):
        self.nil = Node(None)
        self.nil.set_next(self.nil)
        self.nil.set_prev(self.nil)

    def insert(self, x):
        new_elem = Node(x)
        new_elem.set_next(self.nil.next)
        new_elem.set_prev(self.nil)
        self.nil.next.set_prev(new_elem)
        self.nil.set_next(new_elem)

    def list_search(self, x):
        cur = self.nil.next
        while cur != self.nil and cur.x != x:
            cur = cur.next
        return cur

    def _delete(self, node):
        node.prev.set_next(node.next)
        node.next.set_prev(node.prev)

    def delete_first(self):
        self._delete(self.nil.next)

    def delete_last(self):
        self._delete(self.nil.prev)

    def delete(self, x):
        del_node = self.list_search(x)
        if del_node.x is not None:
            self._delete(del_node)


def main():
    d_linked_list = DoublelyLinkedList()
    for i in sys.stdin:
        if 'insert' in i:
            x = i[7:-1]
            d_linked_list.insert(x)
        elif 'deleteFirst' in i:
            d_linked_list.delete_first()
        elif 'deleteLast' in i:
            d_linked_list.delete_last()
        elif 'delete' in i:
            x = i[7:-1]
            d_linked_list.delete(x)
        else:
            pass

    results = []
    cur = d_linked_list.nil.next
    while cur.x is not None:
        results.append(cur.x)
        cur = cur.next

    print(*results)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

N=int(input())
array=deque()
for n in range(N):
    bun=input()
    if bun=='deleteFirst':
        del array[0]
    elif bun=='deleteLast':
        del array[-1]
    else:
        order,num=bun.split()
        if order=='insert':
            array.insert(0,num)
        else:
            try:array.remove(num)
            except:pass
print(' '.join(array))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

class Node:
  def __init__(self,key):
    self.key=key
    self.prev=None
    self.next=None

class LinkedList:
  first=None
  last=None
  current=first

  def insert(self,x):
    node=Node(x)
    self.current=node
    if self.first==None:
      self.first=node
      self.last=node
    else:
      self.first.prev=node
      node.next=self.first
      self.first=node
  
  def delete(self,x):
    if self.first==None:
      #print('Error')
      return
    if self.first==self.last and self.first.key==x:
      self.first=None
      self.current=None
      self.last=None
      return

    elif self.first.key==x:
      self.first.next.prev=None
      self.current=self.first.next
      self.first=self.first.next
      return

    tmp=self.first
    while tmp!=None:
      if self.last==tmp and tmp.key==x:
        self.last.prev.next=None
        self.last=self.last.prev
        break
      elif tmp.key==x:
        tmp.prev.next=tmp.next
        tmp.next.prev=tmp.prev
        break
      tmp=tmp.next

  def deleteFirst(self):
    if self.first==self.last:
      self.first=None
      self.last=None
      self.current=None
      return
    self.first.next.prev=None
    self.first=self.first.next
    self.current=self.first

  def deleteLast(self):
    if self.first==self.last:
      self.first=None
      self.last=None
      self.current=None
      return
    self.last.prev.next=None
    self.last=self.last.prev

  def next(self):
    if self.current==None:
      return None
    tmp=self.current
    self.current=self.current.next
    return tmp

if __name__ == '__main__':
  n=int(input())
  L=LinkedList()

  def answer():
    tmp=L.next()
    while tmp!=None:
      ans=tmp.key
      tmp=L.next()
      if tmp==None:
        print(ans)
      else:
        print(ans,end=' ')
    L.current=L.first

  for _ in range(n):
    S=input().split()
    #print('---')
    #print(*S)
    if S[0]=='insert':
      L.insert(S[1])
    elif S[0]=='delete':
      L.delete(S[1])
    elif S[0]=='deleteFirst':
      L.deleteFirst()
    elif S[0]=='deleteLast':
      L.deleteLast()
    #answer()
  answer()

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


class DoublyLinkedNode(object):
    def __init__(self, front, data, back):
        self.front = front
        self.data = data
        self.back = back


class DoublyLinkedList(object):
    def __init__(self):
        self.first_node = None
        self.last_node = None

    def insert(self, data):
        if self.first_node is None:
            self.first_node = DoublyLinkedNode(None, data, None)
            self.last_node = self.first_node
        else:
            second_node = self.first_node
            self.first_node = DoublyLinkedNode(None, data, second_node)
            second_node.front = self.first_node

    def delete(self, data):
        node = self.first_node
        while node:
            if node.data == data:
                if node == self.first_node:
                    self.delete_first()
                    break
                elif node == self.last_node:
                    self.delete_last()
                    break
                else:
                    node.front.back = node.back
                    node.back.front = node.front
                    break
            else:
                node = node.back

    def delete_first(self):
        if self.first_node.back is None:
            self.__init__()
        else:
            self.first_node = self.first_node.back
            self.first_node.front = None

    def delete_last(self):
        if self.last_node.front is None:
            self.__init__()
        else:
            self.last_node = self.last_node.front
            self.last_node.back = None

    def show_all(self):
        data_list = []
        node = self.first_node
        while node:
            data_list.append(node.data)
            node = node.back
        print(" ".join(map(str, data_list)))


def main():
    n = int(input())
    link = DoublyLinkedList()
    for _ in range(n):
        command = input().rstrip()
        if command == "deleteFirst":
            link.delete_first()
        elif command == "deleteLast":
            link.delete_last()
        else:
            command = command.split()
            command, data = command[0], int(command[1])
            if command == "insert":
                link.insert(data)
            elif command == "delete":
                link.delete(data)
            else:
                raise ValueError
    link.show_all()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
x = deque()

for i in range(int(input())):
    com = input()
    if com == "deleteFirst":
        x.popleft()
    elif com == "deleteLast":
        x.pop()
    else:
        com,n = com.split()
        if com == "insert":
            x.appendleft(n)
        elif com == "delete":
            try:
                x.remove(n)
            except:
                pass
            
print(*x)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
import collections

class DoublyLinkedList_deque:
    def __init__(self):
        self.doubly_linked_list = collections.deque()

    def execute(self,cmd, key):
        if cmd == 'insert':
            self.doubly_linked_list.appendleft(key)
        elif cmd == 'delete':
            try:
                self.doubly_linked_list.remove(key)
            except:
                pass
        elif cmd == 'deleteFirst':
            self.doubly_linked_list.popleft()
        elif cmd == 'deleteLast':
            self.doubly_linked_list.pop()
        else:
            print("invalid cmd")

n = int(stdin.readline().rstrip())
obj_dll = DoublyLinkedList_deque()
for i in range(n):
    input_str=stdin.readline().rstrip().split()
    cmd = input_str[0]
    x = input_str[1] if len(input_str)>1 else None
    obj_dll.execute(cmd,x)
else:
    print(*obj_dll.doubly_linked_list)

Submission status: Accepted

Solution code:
import sys
from collections import deque
N = int(sys.stdin.readline())
lines = sys.stdin.readlines()

l = deque()
for i in range(N):
    command = lines[i].split()
    if command[0] == 'deleteFirst':
        l.popleft()
    elif command[0] == 'deleteLast':
        l.pop()
    elif command[0] == 'insert':
        l.appendleft(command[1])
    else:
        if command[1] in l:
            l.remove(command[1])
            
print(' '.join(map(str, l)))