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: Wrong Answer

Solution code:
import sys

class Deque:
    class Cell2:
        def __init__(self, x, y = None, z = None):
            self.data = x
            self.next = y
            self.prev = z

    def __init__(self):
        head = Deque.Cell2(None)
        head.next = head        
        head.prev = head
        self.size = 0
        self.head = head

    def push_front(self, x):
        h = self.head
        q = h.next
        p = Deque.Cell2(x, q, h)
        h.next = p
        q.prev = p
        self.size += 1

    def pop_back(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.prev
        p = q.prev
        p.next = h
        h.prev = p
        self.size -= 1
        return q.data

    def pop_front(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.next
        p = q.next
        p.prev = h
        h.next = p
        self.size -= 1
        return q.data

    def delete(self,x):
        h=self.head.next
        while h.data!=x:
            h=h.next
            if h==self.head: raise IndexError
        q=h.next
        p=h.prev
        q.prev=p
        p.next=q
        self.size -= 1
        return

    def __str__(self):
        if self.size == 0: return
        buff = ''
        n = self.size
        cp = self.head.next
        while n > 1:
            buff += '%s, ' % cp.data
            cp = cp.next
            n -= 1
        buff += '%s' % cp.data
        return buff
    
A=Deque()
n=int(raw_input())
while n:
    s = (raw_input().split())
    if s[0] == 'insert':
        A.push_front(s[1])
    elif s[0] == 'delete':
        A.delete(s[1])
    elif s[0] == 'deleteFirst':
        A.pop_front()
    elif s[0] == 'deleteLast':
        A.pop_back()
    n -=1
    
print A

Submission status: Wrong Answer

Solution code:
import sys,gc

class Deque:
    class Cell2:
        def __init__(self, x, y = None, z = None):
            self.data = x
            self.next = y
            self.prev = z

    def __init__(self):
        head = Deque.Cell2(None)
        head.next = head        
        head.prev = head
        self.size = 0
        self.head = head

    def push_front(self, x):
        h = self.head
        q = h.next
        p = Deque.Cell2(x, q, h)
        h.next = p
        q.prev = p
        self.size += 1

    def pop_back(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.prev
        p = q.prev
        p.next = h
        h.prev = p
        self.size -= 1
        return q.data

    def pop_front(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.next
        p = q.next
        p.prev = h
        h.next = p
        self.size -= 1
        return q.data

    def delete(self,x):
        h=self.head.next
        while h.data!=x:
            h=h.next
            if h==self.head: return
        q=h.next
        p=h.prev
        q.prev=p
        p.next=q
        self.size -= 1
        return

    def __str__(self):
        if self.size == 0: return
        buff = ''
        n = self.size
        cp = self.head.next
        while n > 1:
            buff += '%s ' % cp.data
            cp = cp.next
            n -= 1
        buff += '%s' % cp.data
        return buff
    
A=Deque()
n=int(raw_input())
while n:
    s = (raw_input().split())
    if s[0] == 'insert':
        A.push_front(int(s[1]))
    elif s[0] == 'delete':
        A.delete(int(s[1]))
    elif s[0] == 'deleteFirst':
        A.pop_front()
    elif s[0] == 'deleteLast':
        A.pop_back()
    n -=1
    
    print A
    print

Submission status: Wrong Answer

Solution code:
#coding: utf-8
import sys,gc

    
A=[]
n=int(raw_input())
while n:
    s = (raw_input().split())
    if s[0] == 'insert':
        A.insert(0,s[1])
    elif s[0] == 'delete':
        try:
            A.remove(s[1])
        except:
            pass
    elif s[0] == 'deleteFirst':
        A.pop(0)
    elif s[0] == 'deleteLast':
        A.pop()
    n -=1
    
print A

Submission status: Wrong Answer

Solution code:
import sys,gc

    
A=[]
n=int(raw_input())
while n:
    s = (raw_input().split())
    if s[0] == 'insert':
        A.insert(0,s[1])
    elif s[0] == 'delete':
        try:
            A.remove(s[1])
        except:
            pass
    elif s[0] == 'deleteFirst':
        A.pop(0)
    elif s[0] == 'deleteLast':
        A.pop()
    n -=1
    
print A
print

Submission status: Wrong Answer

Solution code:
import sys

    
A=[]
n=int(raw_input())
while n:
    s = (raw_input().split())
    if s[0] == 'insert':
        A.insert(0,int(s[1]))
    elif s[0] == 'delete':
        try:
            A.remove(int(s[1]))
        except:
            pass
    elif s[0] == 'deleteFirst':
        A.pop(0)
    elif s[0] == 'deleteLast':
        A.pop()
    n -=1
    
print A

Submission status: Wrong Answer

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(s[7:])
        fp += 1
    elif s[6] == ' ':
        i=-1
        try:
            while True:
                i = A[i+1:].index(s[7:])
        except:
            if i!=-1:
                del A[i]
                fp -=1
    elif s[6] == 'F':
        A.pop()
        fp -=1
    elif s[6] == 'L':
        bp +=1
    n -=1
    print A

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin
n = int(stdin.readline())
dll = []
while n:
    n -= 1
    cmd = stdin.readline().rstrip()
    print(cmd)
    if cmd.startswith('insert '):
        dll.insert(0, cmd[7:])
    elif cmd.startswith('delete '):
        i = dll.index(cmd[7:])
        if i >= 0:
            del dll[i]
    elif cmd.startswith('deleteFirst'):
        del dll[0]
    elif cmd.startswith('deleteLast'):
        del dll[-1]
    print(*dll)
print(*dll)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#from __future__ import print_function
import time
import sys
import io
import re
import math
start = time.clock()
i = 0
ans=[]
#n=int(raw_input())
#for _ in range(n):
for _ in range(int(raw_input())):
#    a=sys.stdin.readline().split()
    a=sys.stdin.readline().strip()
#    chk=a[0]
    chk=a[6]
    if a[0]=='i': ans.insert(0,a[7:])
#    elif chk=='deleteFirst': ans.pop(0)
    elif chk=='F': del ans[0]
#    elif chk=='deleteLast': ans.pop()
    elif chk=='L': del ans[-1]
#    else: ans.remove(str(a[1]))
    else:
#        if a[1] in ans:
        if ans.count(a[7:])>0:
            ans.remove(a[7:])
for j in ans:
    print ans

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#from __future__ import print_function
import time
import sys
import io
import re
import math
start = time.clock()
i = 0
ans=[]
#n=int(raw_input())
#for _ in range(n):
for _ in range(int(raw_input())):
#    a=sys.stdin.readline().split()
    a=sys.stdin.readline().strip()
#    chk=a[0]
    chk=a[6]
    if a[0]=='i': ans.insert(0,a[7:])
#    elif chk=='deleteFirst': ans.pop(0)
    elif chk=='F': del ans[0]
#    elif chk=='deleteLast': ans.pop()
    elif chk=='L': del ans[-1]
#    else: ans.remove(str(a[1]))
    else:
#        if a[1] in ans:
        if ans.count(a[7:])>0:
            ans.remove(a[7:])
for j in ans:
    print ans,

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#from __future__ import print_function
import time
import sys
import io
import re
import math
start = time.clock()
i = 0
ans=[]
#n=int(raw_input())
#for _ in range(n):
for _ in range(int(raw_input())):
#    a=sys.stdin.readline().split()
    a=sys.stdin.readline().strip()
#    chk=a[0]
    chk=a[6]
#    if a[0]=='i': ans.insert(0,a[7:])
    if a[0]=='i': ans.append(a[7:])
#    elif chk=='deleteFirst': ans.pop(0)
    elif chk=='F': del ans[0]
#    elif chk=='deleteLast': ans.pop()
    elif chk=='L': del ans[-1]
#    else: ans.remove(str(a[1]))
    else:
#        if a[1] in ans:
#        if ans.count(a[7:])>0:
        try:
            ans.remove(a[7:])
        except:
            pass
for j in ans:
    print int(j),

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#from __future__ import print_function
import time
import sys
i = 0
ans=[]
#n=int(raw_input())
#for _ in range(n):
for _ in range(int(raw_input())):
    a=sys.stdin.readline().strip()
    chk=a[6]
    if a[0]=='i': ans.append(a[7:])
    elif chk=='F': del ans[0]
    elif chk=='L': del ans[-1]
    else:
        try:
            ans.remove(a[7:])
        except:
            pass
ans=ans[::-1]
#for j in ans:
#    print int(j),
#print ans
#    print ans
print ' '.join(ans)

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = ""
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls = cmd[1] + ls
    elif cmd[0] == "delete":
        p = ls.index(cmd[1])
        ls = ls[:p] + ls[p+1:]
    elif cmd[0] == "deleteFirst":
        ls = ls[1:]
    elif cmd[0] == "deleteLast":
        ls = ls[:len(ls)-1]

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

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = []
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls.insert(0, cmd[1])
    elif cmd[0] == "delete":
        ls.remove(cmd[1])
    elif cmd[0] == "deleteFirst":
        del ls[:1]
    elif cmd[0] == "deleteLast":
        del ls[len(ls)-1:]
    print ls
print " ".join(map(str, ls))

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = []
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls.insert(0, cmd[1])
    elif cmd[0] == "delete":
        if ls.count(cmd[1]) > 0:
            ls.remove(cmd[1])
    elif cmd[0] == "deleteFirst":
        del ls[:1]
    elif cmd[0] == "deleteLast":
        del ls[len(ls)-1:]
    print ls
print " ".join(map(str, ls))

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = []
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls.append(cmd[1])
    elif cmd[0] == "deleteFirst":
        del ls[len(ls)-1:]
    elif cmd[0] == "deleteLast":
        del ls[1:]
    else:
        for i in range(len(ls)-1,0,-1):
            if ls[i] == cmd[1]:
                a = ls.pop(i)
print " ".join(map(str, ls[::-1]))

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = []
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls.append(cmd[1])
    elif cmd[0] == "deleteFirst":
        del ls[len(ls)-1:]
    elif cmd[0] == "deleteLast":
        del ls[:1]
    else:
        for i in range(len(ls)-1,0,-1):
            if ls[i] == cmd[1]:
                a = ls.pop(i)
print " ".join(map(str, ls[::-1]))

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ls = []
for i in range(n):
    cmd = map(str, raw_input().split())
    if cmd[0] == "insert":
        ls.append(cmd[1])
    elif cmd[0] == "deleteFirst":
        del ls[len(ls)-1:]
    elif cmd[0] == "deleteLast":
        del ls[:1]
    else:
        for i in range(len(ls)-1,-1,-1):
            if ls[i] == cmd[1]:
                a = ls.pop(i)
print " ".join(map(str, ls[::-1]))

Submission status: Wrong Answer

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:
			ls[::-1].remove(cmd[7:])
		except:
			pass
	elif cmd[6] == "F":
		ls.pop()
	else:
		bp += 1

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

Submission status: Wrong Answer

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:
			ls[::-1].remove(cmd[7:])
		except:
			pass
	elif cmd[6] == "F":
		ls.pop()
	else:
		bp += 1

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

Submission status: Wrong Answer

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 ls
print " ".join(map(str, ls[bp:][::-1]))

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())

q = deque()
for i in range(n):
    cmd = input().strip().split()
    if cmd[0] == 'insert':
        q.appendleft(cmd[1])
        continue
    if cmd[0] == 'delete':
        try:
            q.remove(x)
        except:
            pass
        continue
    if cmd[0] == 'deleteFirst':
        q.popleft()
        continue
    if cmd[0] == 'deleteLast':
        q.pop()
        continue

print(' '.join(q))

Submission status: Wrong Answer

Solution code:
n = int(input())
q = []
bottom = -1
for i in range(n):
    print(' '.join(q[bottom::-1]))
    cmd = 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: Wrong Answer

Solution code:
n = int(input())
q = []
bottom = -1
for i in range(n):
    cmd = 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: Time Limit Exceeded

Solution code:
#coding:utf-8
dic = {}
nil = -1

class Doubly:
    def __init__(self,key,l=nil,r=nil):
        self.l = l
        self.r = r
        self.key = key

    def Insert(self,key):
        obj = Doubly(key)
        obj.l = fake
        fakeR = fake.r
        fake.r = obj
        obj.r = fakeR
        fakeR.l = obj
        if key in dic.keys():
            dic[key].append(obj)
        else:
            dic[key] = [obj]
    def deleteFirst(self):
        fakeR = fake.r
        fake.r = fakeR.r
        fakeR.r.l = fake
        key = fakeR.key
        if dic != {}:
            dic[key].pop()
            if dic[key] == []:
                del dic[key]

    def deleteLast(self):
        fakeL = fake.l
        fake.l = fakeL.l
        fakeL.l.r = fake
        key = fakeL.key
        if dic != {}:
            dic[key].pop(0)
            if dic[key] == []:
                del dic[key]
        

    def Delete(self,target):
        if target in dic.keys():
            obj = dic[target].pop()
            objL = obj.l
            objR = obj.r
            objL.r = objR
            objR.l = objL
            if dic[target] == []:
                del dic[target]
        


n = int(input())

fake = Doubly(nil)
fake.l = fake
fake.r = fake


for i in range(n):
    data = list(input().split())
    order = data[0]
    if order == "insert":
        Doubly.Insert(Doubly, int(data[1]))
    elif order == "delete":
        Doubly.Delete(Doubly, int(data[1]))
    elif order == "deleteFirst":
        Doubly.deleteFirst(Doubly)
    else:
        Doubly.deleteLast(Doubly)

obj = fake.r
List = []
while obj.key != -1:
    List.append(str(obj.key))
    obj = obj.r

print(" ".join(List))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
n = int(input())

class LinkedList:
    class Cell:
        def __init__(self, x, y=None, z=None):
            # セルを構成（ｘが値、ｙが次のセルの値、ｚが前のセルの値）
            self.data = x
            self.nex = y
            self.pre = z

    def __init__(self, *args):
        head = LinkedList.Cell(None)# オブジェクトを作る準備
        head.nex = head #ヘッダーの右隣のセル
        head.pre = head #ヘッダーの左隣のセル
        self.size = 0
        self.head = head #ヘッダー

    def push_front(self, x):
        h = self.head###ヘッダーのオブジェクトを呼び出し
        q = h.nex   ###qはヘッダーの右隣のセルをｑとおく
        p = LinkedList.Cell(x, q, h) #ｘを値とするセルｐの作成
        h.nex = p #ヘッダーの右隣のセルをｐとする
        q.pre = p #ｑのセルをｐとする
        self.size += 1

    def push_back(self, x):
        h = self.head
        p = h.pre
        q = LinkedList.Cell(x, h, p)
        h.pre = q
        p.next = q
        self.size += 1

    def pop_front(self):
        h = self.head
        q = h.nex
        p = q.nex
        p.pre = h
        h.nex = p
        self.size -= 1

    def pop_back(self):
        h = self.head
        p = h.pre
        q = p.pre
        q.nex = h
        h.pre = q
        self.size -= 1

    def delete(self, x):
        cp = self.head
        i = 0
        while i < self.size:
            i += 1
            cp = cp.nex
            if cp.data == x:
                cp_pre = cp.pre
                cp_nex = cp.nex
                cp_pre.nex = cp_nex
                cp_nex.pre = cp_pre
                self.size -= 1
                return cp.data
        return None
            

l = LinkedList()
for i in range(n):
    order = list(input().split())
    if order[0] == "insert":
        l.push_front(order[1])
    elif order[0] == "delete":
        l.delete(order[1])
    elif order[0] == "deleteFirst":
        l.pop_front()
    else:
        l.pop_back()

head = l.head
numList = []
for i in range(l.size):
    head = head.nex
    numList.append(head.data)

numList = " ".join([str(num) for num in numList])
print(numList)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
list=[]
for i in range(n):
    A=input().split()
    if A[0]=="insert":
        a=int(A[1])
        list.insert(0,a)
    elif A[0]=="delete":
        a=int(A[1])
        if list.count(a)>0: 
            list.remove(a)
    else:
        if A[0]=="deleteFirst":
            list.pop(0)
        elif A[0]=="deleteLast":
            n=len(list)
            list.pop(n-1)
for i in range(len(list)-1):
    print(list[i],end=" ")
print(list[len(list)-1])

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedListNode:
    def __init__(self, num):
        self.num  = num
        self.next = None
        self.prev = None

    def setNext(self, node):
        self.next = node

    def setPrev(self, node):
        self.prev = node

    def getNum(self):
        return self.num

    def getNext(self):
        return self.next

    def getPrev(self):
        return self.prev

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

    def insert(self, x):
        node = DoublyLinkedListNode(x)

        if self.first == None:
            self.first = node
            self.last  = node
            return

        self.first.setPrev(node)
        node.setNext(self.first)

        self.first = node

    def delete(self, x):
        node = self.first

        while node != None:
            if node.getNum() == x:
                if id(node) == id(self.first):
                    self.deleteFirst()
                    break

                if id(node) == id(self.last):
                    self.deleteLast()
                    break

                pnode = node.getPrev()
                nnode = node.getNext()

                if pnode != None:
                    pnode.setNext(nnode)
                if nnode != None:
                    nnode.setPrev(pnode)

                break

            node = node.getNext()

    def deleteFirst(self):
        node = self.first.getNext()

        if node == None:
            self.first = None
            self.last  = None
            return

        node.setPrev(None)
        self.first = node

    def deleteLast(self):
        node = self.last.getPrev()
        if node == None:
            self.first = None
            self.last  = None
            return

        node.setNext(None)
        self.last = node

    def __iter__(self):
        self._it = self.first
        return self

    def __next__(self):
        node = self._it
        if node == None:
            raise StopIteration

        self._it = self._it.getNext()
        return node.getNum()

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

    lst = DoublyLinkedList()

    for _ in range(n):
        cmds = input().split()

        if 'insert' == cmds[0]:
            lst.insert(int(cmds[1]))
        if 'delete' == cmds[0]:
            lst.delete(int(cmds[1]))
        if 'deleteFirst' == cmds[0]:
            lst.deleteFirst()
        if 'deleteLast' == cmds[0]:
            lst.deleteLast()

    print(" ".join([str(x) for x in lst]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedListNode:
    def __init__(self, num):
        self.num  = num
        self.next = None
        self.prev = None

    def setNext(self, node):
        self.next = node

    def setPrev(self, node):
        self.prev = node

    def getNum(self):
        return self.num

    def getNext(self):
        return self.next

    def getPrev(self):
        return self.prev

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

    def insert(self, x):
        node = DoublyLinkedListNode(x)

        if self.first == None:
            self.first = node
            self.last  = node
            return

        self.first.setPrev(node)
        node.setNext(self.first)

        self.first = node

    def delete(self, x):
        node = self.first

        while node != None:
            if node.getNum() == x:
                if id(node) == id(self.first):
                    self.deleteFirst()
                    break

                if id(node) == id(self.last):
                    self.deleteLast()
                    break

                pnode = node.getPrev()
                nnode = node.getNext()

                if pnode != None:
                    pnode.setNext(nnode)
                if nnode != None:
                    nnode.setPrev(pnode)

                break

            node = node.getNext()

    def deleteFirst(self):
        node = self.first.getNext()

        if node == None:
            self.first = None
            self.last  = None
            return

        node.setPrev(None)
        self.first = node

    def deleteLast(self):
        node = self.last.getPrev()
        if node == None:
            self.first = None
            self.last  = None
            return

        node.setNext(None)
        self.last = node

    def __iter__(self):
        self._it = self.first
        return self

    def __next__(self):
        node = self._it
        if node == None:
            raise StopIteration

        self._it = self._it.getNext()
        return node.getNum()

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

    lst = DoublyLinkedList()

    for _ in range(n):
        cmds = input().split()

        if 'insert' == cmds[0]:
            lst.insert(int(cmds[1]))
        if 'delete' == cmds[0]:
            lst.delete(int(cmds[1]))
        if 'deleteFirst' == cmds[0]:
            lst.deleteFirst()
        if 'deleteLast' == cmds[0]:
            lst.deleteLast()

    sep = ''
    for n in lst:
        print(sep+str(n), end='')
        sep = ' '
    print()

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

# 命令数入力
n = int(input())
# 命令入力
order_list = [input().split() for i in range(n)]


# 双方向連結リスト
doubly_linked_list = deque()

for order in order_list:
    
   
    
    if order[0] == "insert":
        doubly_linked_list.appendleft(order[1])
    
    elif order[0] == "delete":
        if order[1] in doubly_linked_list:
            doubly_linked_list.remove(order[1])
    
    elif order[0] =="deleteFirst":
        doubly_linked_list.popleft()
    
    elif order[0] == "deleteLast":
        doubly_linked_list.pop()
        
# 最終結果出力
print(*doubly_linked_list)

Submission status: Time Limit Exceeded

Solution code:
class Node():
    def __init__(self, key):
        self.prev = None
        self.next = None
        self.key = key
    
class Solution:
    def display(self):
        result = []
        cur = nil.next
        while True:
            if cur == nil:
                break
            result.append(cur.key)
            cur = cur.next
        return result
    
    def insert(self, key):
        x = Node(key)

        if nil.next == None:
            nil.next = x
            nil.prev = x
            x.prev = nil
            x.next = nil
        else:
            x.next = nil.next
            nil.next.prev = x
            nil.next = x
            x.prev = nil

    def listSearch(self, key):
        cur = nil.next
        while cur != nil:
            if cur.key == key:
                break
            cur = cur.next
        return cur
    
    def deleteNode(self, node):
        if node == nil:
            return
        node.prev.next = node.next
        node.next.prev = node.prev

    def delete(self, key):
        self.deleteNode(self.listSearch(key))
    
    def deleteFirst(self):
        self.deleteNode(nil.next)
    
    def deleteLast(self):
        self.deleteNode(nil.prev)


myList = Solution()
nil = Node(None)

for _ in range(int(input())):
    s = input()
    try:
        com, val = s.split()
        val = int(val)
    except ValueError:
        com = s
    
    if com == 'insert':
        myList.insert(val)
    elif com == 'delete':
        myList.delete(val)
    elif com == 'deleteFirst':
        myList.deleteFirst()
    elif com == 'deleteLast':
        myList.deleteLast()

print(*myList.display())

Submission status: Time Limit Exceeded

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

for _ in range(int(input())):
    s = input()
    try:
        com, val = s.split()
        val = int(val)
    except ValueError:
        com = s
    
    if com == 'insert':
        d.appendleft(val)
    elif com == 'delete':
        try:
            d.remove(val)
        except:
            pass
    elif com == 'deleteFirst':
        d.popleft()
    elif com == 'deleteLast':
        d.pop()

print(*d)

Submission status: Time Limit Exceeded

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

for _ in range(int(input())):
    s = input().split()
    
    if s[0] == 'insert':
        d.appendleft(int(s[1]))
    elif s[0] == 'delete':
        try:
            d.remove(int(s[1]))
        except:
            pass
    elif s[0] == 'deleteFirst':
        d.popleft()
    elif s[0] == 'deleteLast':
        d.pop()

print(*d)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
q = deque()
for _ in range(int(input())):
    c, *k = input().split()
    k = k[0] if k else None
    if c == 'insert':
        q.appendleft(k)
    elif c == 'delete':
        if k in q:
            q.remove(k)
    elif c == 'deleteFirst':
        q.popleft()
    else:
        q.pop()
print(*q)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
q = deque()
for _ in range(int(input())):
    c, *k = input().split()
    k = k[0] if k else None
    if c[0] == 'i':
        q.appendleft(k)
    elif c[0] == 'd':
        if c[6:7] == 'F':
            q.popleft()
        elif c[6:7] == 'L':
            q.pop()
        else:
            if k in q:
                q.remove(k)
print(*q)

Submission status: Time Limit Exceeded

Solution code:

class Node(object):

    def __init__(self, _pre, _next, value):
        self._pre = _pre
        self._next = _next
        self._value = value

    @property
    def pre(self):
        return self._pre

    @pre.setter
    def pre(self, _pre):
        self._pre = _pre

    @property
    def next(self):
        return self._next

    @next.setter
    def next(self, _next):
        self._next = _next

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, _value):
        self._value = _value


class DoublyLinkedList(object):

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

    def first(self):
        '''return first node of list'''
        return self.dummy.next

    def last(self):
        '''return last node of list'''
        return self.dummy.pre

    def end(self):
        return self.dummy

    def insert_after(self, value, node):
        '''考え方として、Valueをうけとって、クラス内でノードを自己で作成する。'''
        new_node = Node(node.pre, node, value)
        node.pre.next = new_node
        node.pre = new_node

    def insert(self, value):
        self.insert_after(value, self.first())

    def search(self, key):
        n = self.first()
        while n != self.end() and n.value != key:
            n = n.next
        return n

    def print_all(self):
        n = self.first()
        result = []
        while n != self.end():
            result.append(str(n.value))
            n = n.next
        return " ".join(result)


    def delete(self, key, n=None):
        '''ポインターの結合を外すことで削除とする。'''
        if n is None: n = self.search(key)
        n.pre.next = n.next
        n.next.pre = n.pre

    def deleteFirst(self):
        self.delete(None, self.first())

    def deleteLast(self):
        self.delete(None, self.last())


_list = DoublyLinkedList()

n = input()

for _ in range(int(n)):
    com, num = None, None
    com, *num = input().split()

    if num:
        if com == "insert":
            _list.insert(*num)
        else:
            _list.delete(*num)
    else:
        if com == "deleteFirst":
            _list.deleteFirst()
        else:
            _list.deleteLast()



print(_list.print_all())