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
n = int(input())
a = deque()
for i in range(n):
    c = input()
    if c == "deleteFirst":
        a.popleft()
    elif c == "deleteLast":
        a.pop()
    else:
        c, v = c.split()
        if c == "insert":
            a.appendleft(v)
        else:
            try:
                a.remove(v)
            except:
                pass
print(" ".join(a))

Submission status: Accepted

Solution code:
#! python3
# doubly_linked_list.py

from collections import deque

keys = deque([])

n = int(input())

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

print(' '.join([str(k) for k in keys]))

Submission status: Accepted

Solution code:
import collections
a=collections.deque()
for _ in range(int(input())):
    b=input()
    if b[0]=='i':a.appendleft(b[7:])
    elif b[6]==' ':
        try:a.remove(b[7:])
        except:pass
    elif len(b)>10:a.popleft()
    elif len(b)>6:a.pop()
print(*a)

Submission status: Accepted

Solution code:
import sys


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


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


def insert(double_lst, key):
    node = Node(key, double_lst.nil, double_lst.nil.next)
    double_lst.nil.next.prev = node
    double_lst.nil.next = node


def search(double_lst, key):
    cur = double_lst.nil.next

    while cur != double_lst.nil and cur.key != key:
        cur = cur.next

    return cur


def delete_node(double_lst, node):
    if node == double_lst.nil:
            return

    node.prev.next = node.next
    node.next.prev = node.prev


def delete_first(double_lst):
    delete_node(double_lst, double_lst.nil.next)


def delete_last(double_lst):
    delete_node(double_lst, double_lst.nil.prev)


def delete_key(double_lst, key):
    node = search(double_lst, key)
    delete_node(double_lst, node)


def main():
    n = int(input())
    ll = LinkedList()

    for i in range(n):
        order = sys.stdin.readline().split()

        if order[0] == "insert":
            insert(ll, int(order[1]))
        elif order[0] == "delete":
            delete_key(ll, int(order[1]))
        elif order[0] == "deleteFirst":
            delete_first(ll)
        else:
            delete_last(ll)

    cur = ll.nil
    while cur.next != ll.nil:
        cur = cur.next
        if cur.next == ll.nil:
            print(cur.key)
        else:
            print(cur.key, end=" ")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
n = int(input())
deq = deque()
sub_deq = {}
for cmd in sys.stdin.readlines():
    if cmd == 'deleteFirst\n':
        while deq:
            data = deq.pop()
            if data[1]:
                data[1] = 0
                break
    elif cmd == 'deleteLast\n':
        while deq:
            data = deq.popleft()
            if data[1]:
                data[1] = 0
                break
    else:
        cmd, val = cmd.split()
        if cmd == 'insert':
            data = [val, 1]
            deq.append(data)
            if val not in sub_deq:
                sub_deq[val] = [data]
            else:
                sub_deq[val].append(data)
        elif cmd == 'delete':
            if val in sub_deq:
                deq_v = sub_deq[val]
                while deq_v:
                    data = deq_v.pop()
                    if data[1]:
                        data[1] = 0
                        break
sys.stdout.write(" ".join(data[0] for data in reversed(deq) if data[1]))
sys.stdout.write('\n')

Submission status: Accepted

Solution code:
from collections import deque

def pr(A,n):
    for i in range(n):
        if i!=n-1:
            print(A[i],end=" ")
        else:
            print(A[i])

n=int(input())
que_r=deque()
data=deque()

for i in range(n):
    s=input()
    l=len(s)
    if s[0]=="i":
        que_r.appendleft(s[7:])
    elif s[6]==" ":
        try:
            que_r.remove(s[7:])
        except: pass
    elif l>10:
        que_r.popleft()
    elif l>6:
        que_r.pop()

pr(que_r,len(que_r))

Submission status: Accepted

Solution code:
from collections import deque

n=int(input())
que_r=deque()

for i in range(n):
    s=input()
    l=len(s)
    if s[0]=="i":
        que_r.appendleft(s[7:])
    elif s[6]==" ":
        try:
            que_r.remove(s[7:])
        except: pass
    elif l>10:
        que_r.popleft()
    elif l>6:
        que_r.pop()

print(*que_r)

Submission status: Accepted

Solution code:
from collections import deque


n=int(input())
que_r=deque()

for i in range(n):
    s=input()
    l=len(s)
    if s[0]=="i":
        que_r.appendleft(s[7:])
    elif s[6]==" ":
        try:
            que_r.remove(s[7:])
        except: pass
    elif l>10:
        que_r.popleft()
    elif l>6:
        que_r.pop()

print(*que_r)

Submission status: Accepted

Solution code:
from collections import deque

def pr(a):
    for i in range(len(a)):
        if i == len(a)-1:
            print(a[i])
        else:
            print(a[i],end = " ")

n = int(input())
q = deque()
for i in range(n):
    x = input()
    l = len(x)
    if x[0] == "i":
        q.insert(0,x[7:])
    elif x[6] == " ":
        try:
            q.remove(x[7:])
        except:
            pass
    elif l > 10:
        q.popleft()
    elif l > 6:
        q.pop()

print(*q)

Submission status: Accepted

Solution code:
import collections
x=collections.deque()
for _ in range(int(input())):
    b=input()
    if b[0]=='i':x.appendleft(b[7:])
    elif b[6]==' ':
        try:x.remove(b[7:])
        except:pass
    elif len(b)>10:x.popleft()
    elif len(b)>6:x.pop()
print(*x)

Submission status: Accepted

Solution code:
from collections import deque


n = int(input())
L = deque()

for i in range(n):
    com = input()
    if com[0] == 'i':
        C = com.split()
        L.appendleft(int(C[1]))
    else:
        if com[6] == 'F':
            L.popleft()
        elif com[6] == 'L':
            L.pop()
        else:
            C = com.split()
            x = int(C[1])
            try:
                L.remove(x)
            except:
                pass

print(*L)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
L = deque()

for i in range(n):
    com = input()
    if com[0] == 'i':
        C = com.split()
        L.appendleft(int(C[1]))
    else:
        if com[6] == 'F':
            L.popleft()
        elif com[6] == 'L':
            L.pop()
        else:
            C = com.split()
            x = int(C[1])
            try:
                L.remove(x)
            except:
                pass

print(*L)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#16D8101014F 久留米 竜之介 Kurume Ryunosuke 2018/5/9 python3
import collections 
List=collections.deque()
n=int(input())
for i in range(n):
	command=input().split()
	if command[0] == 'insert':
		List.appendleft(command[1])		
	elif command[0] == 'delete':
		try:
			List.remove(command[1])
		except:
			pass
	elif command[0] == 'deleteFirst':
		List.popleft()	
	elif command[0] == 'deleteLast':
		List.pop()
		
print(*List)

Submission status: Accepted

Solution code:
from collections import deque
a=int(input())
list=deque([])

for i in range(a):
    order=input().split()
    if order[0]=="insert":
        list.appendleft(order[1])
    elif order[0]=="delete":
        if order[1] in list:
            list.remove(order[1])
    elif order[0]=="deleteFirst":
        list.popleft()
    elif order[0]=="deleteLast":
        list.pop()

print(*list)

Submission status: Accepted

Solution code:

import sys
     
A=[]
fp =0
bp =0
 
n=int(raw_input())
while n:
    s = raw_input()
    if s[0] == 'i':
        A.append(int(s[7:]))
        fp += 1
    elif s[6] == ' ':
        try:
            i = A[::-1].index(int(s[7:]))
            if i!=-1:
                del A[-i-1]
                fp -=1
        except:
            pass
    elif s[6] == 'F':
        A.pop()
        fp -=1
    elif s[6] == 'L':
        bp +=1
    n -=1
 
for e in A[bp:fp+1][::-1]:
    print int(e),

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())

linked_list = deque([])

for _ in range(n):
    command = input()

    if "insert" in command:
        x = command.split()[-1]
        linked_list.appendleft(x)
    elif command == "deleteFirst":
        linked_list.popleft()
    elif command == "deleteLast":
        linked_list.pop()
    elif "delete" in command:
        x = command.split()[-1]
        if x in linked_list:
            linked_list.remove(x)

print(*linked_list)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
output = deque()
for i in range(n):
    li = input().split(' ')
    if(li[0] == 'insert'):
        output.appendleft(li[1])
    elif(li[0] == 'deleteFirst'):
        output.popleft()
    elif(li[0] == 'deleteLast'):
        output.pop()
    elif(li[0] == 'delete'):
        try:
            output.remove(li[1])
        except:
            pass
print(' '.join(output))

Submission status: Accepted

Solution code:
import sys


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


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

    def insert(self, x):
        node = Node(key=x, prev=self.head, next=self.head.next)
        self.head.next.prev = node
        self.head.next = node

    def search(self, x):
        node = self.head.next
        while node is not self.head and node.key != x:
            node = node.next
        return node

    def delete_key(self, x):
        node = self.search(x)
        self._delete(node)

    def _delete(self, node):
        if node is self.head:
            return None
        node.prev.next = node.next
        node.next.prev = node.prev

    def deleteFirst(self):
        self._delete(self.head.next)

    def deleteLast(self):
        self._delete(self.head.prev)

    def getKeys(self):
        node = self.head.next
        keys = []
        while node is not self.head:
            keys.append(node.key)
            node = node.next
        return " ".join(keys)


L = DoublyLinkedList()
n = int(input())
for i in sys.stdin:
    if 'insert' in i:
        x = i[7:-1]
        L.insert(x)
    elif 'deleteFirst' in i:
        L.deleteFirst()
    elif 'deleteLast' in i:
        L.deleteLast()
    elif 'delete' in i:
        x = i[7:-1]
        L.delete_key(x)
    else:
        pass
print(L.getKeys())

Submission status: Accepted

Solution code:
import sys


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


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

    def insert(self, x):
        node = Node(key=x, prev=self.head, next=self.head.next)
        self.head.next.prev = node
        self.head.next = node

    def search(self, x):
        node = self.head.next
        while node is not self.head and node.key != x:
            node = node.next
        return node

    def delete_key(self, x):
        node = self.search(x)
        if node is self.head:
            return None
        self._delete(node)

    def _delete(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def deleteFirst(self):
        self._delete(self.head.next)

    def deleteLast(self):
        self._delete(self.head.prev)

    def getKeys(self):
        node = self.head.next
        keys = []
        while node is not self.head:
            keys.append(node.key)
            node = node.next
        return " ".join(keys)


L = DoublyLinkedList()
n = int(input())
for i in sys.stdin:
    if 'insert' in i:
        x = i[7:-1]
        L.insert(x)
    elif 'deleteFirst' in i:
        L.deleteFirst()
    elif 'deleteLast' in i:
        L.deleteLast()
    elif 'delete' in i:
        x = i[7:-1]
        L.delete_key(x)
    else:
        pass
print(L.getKeys())

Submission status: Accepted

Solution code:
import sys
from collections import deque

n = int(input())
ary = deque([])

for line in sys.stdin:
    op = line.strip().split()
    cmd = op[0]

    if cmd[0] == 'i':
        x = op[1]
        ary.appendleft(x)

    elif len(cmd) == 6:
        x = op[1]
        if x in ary:
            ary.remove(x)

    elif len(cmd) == 10:
        ary.pop()

    else:
        ary.popleft()

print(*ary)

Submission status: Accepted

Solution code:
import sys
from collections import deque

n = int(input())
ary = deque([])

for line in sys.stdin:
    op = line.strip().split()
    cmd = op[0]

    if cmd == 'insert':
        x = op[1]
        ary.appendleft(x)

    elif cmd == 'delete':
        x = op[1]
        if x in ary:
            ary.remove(x)

    elif cmd == 'deleteLast':
        ary.pop()

    else:
        ary.popleft()

print(*ary)

Submission status: Accepted

Solution code:
from collections import deque
a = deque([])
for i in range(int(input())):
    c = input().split()
    if c[0] == "insert":
        a.appendleft(c[1])
    elif c[0] == "delete":
        try:
            a.remove(c[1])
        except ValueError:
            pass
    elif c[0] == "deleteFirst":
        a.popleft()
    else:
        a.pop()
for i,e in enumerate(a):
    if i == len(a) - 1:
        print(e)
    else:
        print(e, end=" ")

Submission status: Accepted

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

class LinkedList(object):

    def __init__(self):
        self.dummy = Node(None)
        self.dummy.next = self.dummy
        self.dummy.prev = self.dummy

    def insert(self, x):
        node = Node(x, self.dummy.next, self.dummy)

        self.dummy.next.prev = node
        self.dummy.next = node
    
    def delete(self, x):
        node = self.dummy.next
        while node != self.dummy:
            if node.value == x:
                self.__remove_node(node)
                break
            else:
                node = node.next
    
    def deleteFirst(self):
        self.__remove_node(self.dummy.next)

    def deleteLast(self):
        self.__remove_node(self.dummy.prev)

    def __remove_node(self, node):
        if node != self.dummy:
            node.prev.next = node.next
            node.next.prev = node.prev

    def items(self):
        ret = []
        node = self.dummy.next
        while node != self.dummy:
            ret.append(node.value)
            node = node.next
        return ret

def main():
    from sys import stdin
    store = LinkedList()
    for i in range(int(input())):
        parts = stdin.readline().strip().split()
        cmd = parts[0]
        if cmd == 'insert':
            store.insert(parts[1])
        elif cmd == 'delete':
            store.delete(parts[1])
        elif cmd == 'deleteFirst':
            store.deleteFirst()
        elif cmd =='deleteLast':
            store.deleteLast()

    print(' '.join(store.items()))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())
de = deque()
for n in range(N):
    com = input().split()
    if com[0] == "insert":
        de.appendleft(com[1])
    elif com[0] == "delete":
        try:
            de.remove(com[1])
        except:
            pass
    elif com[0] == "deleteFirst":
        de.popleft()
    else:
        de.pop()
print(*de)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
a = deque()
for i in range(n):
    c = input()
    if c == "deleteFirst":
        a.popleft()
    elif c == "deleteLast":
        a.pop()
    else:
        c, v = c.split()
        if c == "insert":
            a.appendleft(v)
        else:
            try:
                a.remove(v)
            except:
                pass
print(" ".join(a))

Submission status: Accepted

Solution code:
from collections import deque

def run():
    n = int(input())
    dq = deque()
    for _ in range(n):
        order = input()
        if order[0] == 'i':
            dq.appendleft(order[7:])
        elif order[6] == ' ':
            key = order.split()[1]
            if not key in dq:
                continue
            for i in range(len(dq)):
                if dq[i] == key:
                    dq.remove(key)
                    break
        elif order[6] == 'F':
            dq.popleft()
        elif order[6] == 'L':
            dq.pop()

    print(' '.join(dq))

if __name__ == '__main__':
    run()

Submission status: Accepted

Solution code:
from sys import stdin

class DList:
    class Cell:
        def __init__(self, k):
            self.key  = k
            self.prev = None
            self.next = None

    def __init__(self):
        self.head = DList.Cell(None)
        self.last = DList.Cell(None)
        self.head.next = self.last
        self.last.prev = self.head

    def insert(self, x):
        c = DList.Cell(x)
        c.prev = self.head
        c.next = self.head.next
        c.next.prev = c
        self.head.next = c

    def delete(self, x):
        c = self.__find(x)
        if c != None:
            self.__delete(c)

    def __delete(self, c):
        c.prev.next = c.next
        c.next.prev = c.prev

    def __find(self, x):
        c = self.head.next
        while c != None and c.key != x:
            c = c.next
        return c

    def deleteFirst(self):
        self.__delete(self.head.next)
    def deleteLast(self):
        self.__delete(self.last.prev)

    def __iter__(self):
        self.it = self.head.next
        return self
    def __next__(self):
        if self.it == self.last:
            raise StopIteration
        k = self.it.key
        self.it = self.it.next
        return k

dlist = DList()

n = int(stdin.readline())
for i in range(n):
    cmd = stdin.readline()
    if   cmd.startswith('insert'):
        dlist.insert(cmd[7:-1])
    elif cmd.startswith('deleteFirst'):
        dlist.deleteFirst()
    elif cmd.startswith('deleteLast'):
        dlist.deleteLast()
    elif cmd.startswith('delete'):
        dlist.delete(cmd[7:-1])

print(' '.join(dlist))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
l = deque()
for _ in range (n):
    cmd = input().split(' ')
    if cmd[0]=='insert':
        l.appendleft(cmd[1])  
    if cmd[0]=='delete':
        try:l.remove(cmd[1])
        except :pass
    if cmd[0]=='deleteFirst':
        l.popleft()
    if cmd[0]=='deleteLast':
        l.pop()
print(*l)

Submission status: Accepted

Solution code:
n = int(raw_input())
x = [0 for i in range(n)]
pf = -1
pb = 0

li = []
for i in range(n):
    s = (raw_input().split())
    if s[0] == 'insert':
        pf += 1
        x[pf]=int(s[1])
    elif s[0] == 'delete':
        try:
            p = x[pf::-1].index(int(s[1]))
            x[pf-p] = 0
            while x[pf]==0:
                pf -= 1
            while x[pb]==0:
                pb += 1
        except:
            pass
    elif s[0] == 'deleteFirst':
        x[pf]=0
        pf -= 1
    elif s[0] == 'deleteLast':
        x[pb] = 0
        pb += 1
for e in x[pb:pf+1][::-1]:
    if e != 0:
        print e,

Submission status: Accepted

Solution code:
import sys
    
A=[]
fp =0
bp =0

n=int(raw_input())
while n:
    s = raw_input()
    if s[0] == 'i':
        A.append(int(s[7:]))
        fp += 1
    elif s[6] == ' ':
        try:
            i = A[::-1].index(int(s[7:]))
            if i!=-1:
                del A[-i-1]
                fp -=1
        except:
            pass
    elif s[6] == 'F':
        A.pop()
        fp -=1
    elif s[6] == 'L':
        bp +=1
    n -=1

for e in A[bp:fp+1][::-1]:
    print int(e),

Submission status: Accepted

Solution code:
import sys,gc
    
A=[]
fp =0
bp =0

n=int(raw_input())
while n:
    s = raw_input()
    if s[0] == 'i':
        A.append(int(s[7:]))
        fp += 1
    elif s[6] == ' ':
        try:
            i = A[::-1].index(int(s[7:]))
            if i!=-1:
                del A[-i-1]
                fp -=1
        except:
            pass
    elif s[6] == 'F':
        A.pop()
        fp -=1
    elif s[6] == 'L':
        bp +=1
    n -=1

for e in A[bp:fp+1][::-1]:
    print int(e),

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin
from collections import deque

n = int(stdin.readline())
dll = deque()
fcode = ord('F')
lcode = ord('L')
while n:
    n -= 1
    cmd = stdin.readline().rstrip()
    if cmd.startswith('i'):
        dll.appendleft(int(cmd[7:]))
    elif cmd.startswith('d'):
        c = ord(cmd[6])
        if c == fcode:
            dll.popleft()
        elif c == lcode:
            dll.pop()
        else:
            try:
                dll.remove(int(cmd[7:]))
            except ValueError:
                pass
print(*dll)

Submission status: Accepted

Solution code:
n = int(raw_input())
ls = []
bp = 0
for i in range(n):
	cmd = raw_input()
	if cmd[0] == "i":
		ls.append(cmd[7:])
	elif cmd[6] == " ":
		try:
			x = ls[::-1].index(cmd[7:])
			if x!=-1:
				del ls[-x-1]
		except:
			pass
	elif cmd[6] == "F":
		ls.pop()
	else:
		bp += 1

print " ".join(map(str, ls[bp:][::-1]))

Submission status: Accepted

Solution code:
n = int(raw_input())
q = []
bottom = 0
for i in range(n):
    cmd = raw_input()
    if cmd[0] == 'i':
        q.append(cmd[7:])
    elif cmd[6] == ' ':
        try:
            q.pop(~q[::-1].index(cmd[7:]))
        except:
            pass
    elif cmd[6] == 'F':
        q.pop()
    else:
        bottom += 1

print(' '.join(q[bottom:][::-1]))

Submission status: Accepted

Solution code:
from sys import stdin

n = int(stdin.readline())
q = []
bottom = 0
for i in range(n):
    cmd = stdin.readline()[:-1]
    if cmd[0] == 'i':
        q.append(cmd[7:])
    elif cmd[6] == ' ':
        try:
            q.pop(~q[::-1].index(cmd[7:]))
        except:
            pass
    elif cmd[6] == 'F':
        q.pop()
    else:
        bottom += 1

print(' '.join(q[bottom:][::-1]))

Submission status: Accepted

Solution code:
import sys
from collections import deque

n = int(sys.stdin.readline())
q = deque()
for i in range(n):
    cmd = sys.stdin.readline()[:-1]
    if cmd[0] == 'i':
        q.appendleft(cmd[7:])
    elif cmd[6] == ' ':
        try:
            q.remove(cmd[7:])
        except:
            pass
    elif cmd[6] == 'F':
        q.popleft()
    else:
        q.pop()

print(' '.join(q))

Submission status: Accepted

Solution code:
class Node(object):
  def __init__(self, num, prv = None, next = None):
    self.num = num
    self.prv = prv
    self.next = next

class DoublyLinkedList(object):
  def __init__(self):
    self.start = self.last = None

  def insert(self, num):
    new_element = Node(num)

    if self.start is None: # 空の場合
      self.start = self.last = new_element
    else:
      new_element.next = self.start
      self.start.prv = new_element
      self.start = new_element

  def delete(self, target):
    it = self.start
    while it is not None: # 該当する最初のノードを見つける
      if it.num == target:
        if it.prv is None and it.next is None: # ノードが一つだけの時
          self.start = self.last = None
        else:
          if it.prv is not None: # 先頭ではない
            it.prv.next = it.next
          else: # 先頭の場合、先頭の次をstartにする
            self.start = self.start.next
          if it.next is not None:  # 最後ではない場合
            it.next.prv = it.prv
          else: # 最後の場合、最後の一つ前をlastにする
            self.last = self.last.prv
        break
      it = it.next

  def deleteFirst(self):
    if self.start is self.last:
      self.start = self.last = None
    else:
      self.start.next.prv = None
      self.start = self.start.next

  def deleteLast(self):
    if self.start is self.last:
      self.start = self.last = None
    else:
      self.last.prv.next = None
      self.last = self.last.prv

  def contentToArray(self):
    n_list = []
    it  = self.start
    while it is not None:
      n_list.append(it.num)
      it = it.next
    return ' '.join(n_list)

def main():
  from sys import stdin
  N = int(input())

  linkedList = DoublyLinkedList() # インスタンス作成

  for i in range(N):
    command = stdin.readline().rstrip().split()
    if command[0] == 'insert':
      linkedList.insert(command[1])
    elif command[0] == 'delete':
      linkedList.delete(command[1])
    elif command[0] == 'deleteFirst':
      linkedList.deleteFirst()
    elif command[0] == 'deleteLast':
      linkedList.deleteLast()

  print(linkedList.contentToArray())

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
from collections import deque

que = deque()
n = int(input())

for loop in range(n):
    input_command = input()
    
    if input_command == 'deleteFirst':
        que.popleft()
    
    elif input_command == 'deleteLast':
        que.pop()
    
    else:
        command, x = input_command.split()
        
        if command == 'insert':
            que.appendleft(x)
        elif command == 'delete':
            try:
                que.remove(x)
            except:
                pass

print(' '.join(que))

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

    def insert(self,key):
        new = Node(key)
        new.next = self.nil.next
        self.nil.next.prev = new
        self.nil.next = new
        new.prev = self.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 sys import stdin

class Sentinel():
    def __init__(self):
        self.value = None
        self.next = None
        self.prev = None

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

def Insert(key):
    node = Node(key)
    node.next = sent.next
    sent.next.prev = node
    sent.next = node
    node.prev = sent

def Search(key):
    p = sent.next
    while p.value != None:
        if p.value == key:
            return p
        else:
            p = p.next
    return False

def Delete(key):
    p = Search(key)
    if p != False:
        p.prev.next = p.next
        p.next.prev = p.prev

def DeleteF():
    p = sent.next
    p.prev.next = p.next
    p.next.prev = p.prev

def DeleteL():
    p = sent.prev
    p.prev.next = p.next
    p.next.prev = p.prev

sent = Sentinel()
sent.next = sent
sent.prev = sent

n = int(input())
for i in range(n):
    L = stdin.readline().split()
    if L[0] == 'insert':
        Insert(int(L[1]))
    elif L[0] == 'delete':
        Delete(int(L[1]))
    elif  L[0] == 'deleteFirst':
        DeleteF()
    elif  L[0] == 'deleteLast':
        DeleteL()

p = sent.next
tl = []
while True:
    tl.append(p.value)
    p = p.next
    if p.value == None:
        break
print(' '.join(str(x) for x in tl))

Submission status: Accepted

Solution code:
from collections import deque

DLL = deque()

n = int(input())
for _ in range(n):
    command = input()
    if command == 'deleteFirst':
        DLL.popleft()
    elif command == 'deleteLast':
        DLL.pop()
    else:
        command, x = command.split()
        if command == 'insert':
            DLL.appendleft(x)
        elif command == 'delete':
            try:
                DLL.remove(x)
            except ValueError:
                pass
            
print(' '.join(DLL))