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: Time Limit Exceeded

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_C&lang=jp
import sys
input = sys.stdin.readline

class LinkedList():
    def __init__(self):
        self.head = None
    
    def insert(self, x):
        if self.head is None:
            self.head = LinkedListElement(x)
            self.head.next = self.head
            self.head.prev = self.head
            return
        newelm = LinkedListElement(x)
        former_tail = self.head.prev
        former_head = self.head

        former_tail.next = newelm
        former_head.prev = newelm
        
        newelm.next = former_head
        newelm.prev = former_tail
        self.head = newelm

    def deleteLast(self):
        if self.head is None:
            return
        if self.head is self.head.next:
            self.head = None
            return
        
        former_last = self.head.prev
        former_second_last = self.head.prev.prev
        self.head.prev = former_second_last
        former_second_last.next = self.head
    
    def deleteFirst(self):
        if self.head is None:
            return
        if self.head is self.head.next:
            self.head = None
            return

        tail = self.head.prev
        former_second = self.head.next
        tail.next = former_second
        former_second.prev = tail
        self.head = former_second
    
    def delete(self, x):
        if self.head is None:
            return
        if self.head.value == x:
            self.deleteFirst()
            return
        if self.head is self.head.next:
            return
        
        ptr = self.head
        while True:
            if ptr.value == x:
                ptr_prev = ptr.prev
                ptr_next = ptr.next
                ptr_prev.next = ptr_next
                ptr_next.prev = ptr_prev
                break
            ptr = ptr.next
            if ptr is self.head:
                break
    def puts(self):
        if self.head is None:
            print("")
            return
        ptr = self.head
        while True:
            print(ptr.value, end="")
            ptr = ptr.next
            if ptr is self.head:
                print("")
                break
            else:
                print(" ", end="")



class LinkedListElement():

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


if __name__ == "__main__":
    n = int(input())
    li = LinkedList()
    for i in range(n):
        cmd = input().split()
        if cmd[0] == "insert":
            li.insert(cmd[1])
        elif cmd[0] == "delete":
            li.delete(cmd[1])
        elif cmd[0] == "deleteFirst":
            li.deleteFirst()
        elif cmd[0] == "deleteLast":
            li.deleteLast()
    
    li.puts()

Submission status: Time Limit Exceeded

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_C&lang=jp
import sys
input = sys.stdin.readline

class LinkedList():
    def __init__(self):
        self.head = None
        self.N = 0
    
    def insert(self, x):
        self.N += 1
        if self.head is None:
            self.head = LinkedListElement(x)
            self.head.next = self.head
            self.head.prev = self.head
            return
        newelm = LinkedListElement(x)
        former_tail = self.head.prev
        former_head = self.head

        former_tail.next = newelm
        former_head.prev = newelm
        
        newelm.next = former_head
        newelm.prev = former_tail
        self.head = newelm
        

    def deleteLast(self):
        if self.head is None:
            return
        self.N -= 1
        if self.head is self.head.next:
            self.head = None
            return
        
        former_last = self.head.prev
        former_second_last = self.head.prev.prev
        self.head.prev = former_second_last
        former_second_last.next = self.head
    
    def deleteFirst(self):
        if self.head is None:
            return
        self.N -= 1
        if self.head is self.head.next:
            self.head = None
            return

        tail = self.head.prev
        former_second = self.head.next
        tail.next = former_second
        former_second.prev = tail
        self.head = former_second
    
    def delete(self, x):
        if self.head is None:
            return
        if self.head.value == x:
            self.deleteFirst()
            return
        if self.head is self.head.next:
            return
        
        ptr = self.head
        for i in range(self.N):
            if ptr.value == x:
                ptr_prev = ptr.prev
                ptr_next = ptr.next
                ptr_prev.next = ptr_next
                ptr_next.prev = ptr_prev
                self.N -= 1
                break
            ptr = ptr.next

    def puts(self):
        if self.head is None:
            print("")
            return
        ptr = self.head
        for i in range(self.N):
            print(ptr.value, end="")
            ptr = ptr.next
            if i == self.N - 1:
                print("")
                break
            else:
                print(" ", end="")



class LinkedListElement():

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


if __name__ == "__main__":
    n = int(input())
    li = LinkedList()
    for i in range(n):
        cmd = input().split()
        if cmd[0] == "insert":
            li.insert(cmd[1])
        elif cmd[0] == "delete":
            li.delete(cmd[1])
        elif cmd[0] == "deleteFirst":
            li.deleteFirst()
        elif cmd[0] == "deleteLast":
            li.deleteLast()
    
    li.puts()

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self, d, next):
        self.d = d
        self.next = next

    def __str__(self):
        if self.next is None:
            return "(" + self.d + ")"
        else:
            return "(" + self.d + "," + str(self.next) + ")"

# import time

n = int(input())
node = None
for i in range(n):
    # time.sleep(0.1)
    s = input()
    # print(s)
    if s == "deleteFirst":
        node = node.next
    elif s == "deleteLast":
        if node.next is None:
            node = None
        else:
            n = node
            while n.next.next is not None:
                n = n.next
            n.next = None
    else:
        c, d = s.split()
        if c == 'insert':
            n = Node(d, node)
            n.next = node
            node = n
        elif c == "delete":
            n = node
            if n.d == d:
                node = n.next
            else:
                while n.next is not None:
                    if n.next.d == d:
                        n.next = n.next.next
                        break
                    n = n.next
    # print(node)

while node.next is not None:
    d = node.d
    print(d, "", end="")
    node = node.next
print(node.d)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
C = [input() for i in range(n)]

A = []
for c in C:
	if c == 'deleteFirst':
		A.pop(0)
	elif c == 'deleteLast':
		A.pop()
	elif 'delete' in c:
		q = int(c[7:])
		if q in A:
			A.pop(A.index(q))
	elif 'insert' in c:
		q = int(c[7:])
		A.insert(0, q)

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

Submission status: Time Limit Exceeded

Solution code:
class Node():
    def __init__(self,value,front_node,back_node):
        self.value = value
        self.front_node = front_node
        self.back_node = back_node

def insert(value,first_node):
    if first_node == None:
        new_node = Node(value, None, None)
    else:
        new_node = Node(value, None, first_node)
        first_node.front_node = new_node
    first_node = new_node
    return first_node

def delete(chk,first_node):
    flag = True
    next_node = first_node
    while flag:
        if next_node.value == chk:
            flag = False
            if next_node.back_node == None:
                deleteLast(first_node)
            elif next_node.front_node == None:
                first_node = deleteFirst(first_node)
            else:
                next_node.front_node.back_node = next_node.back_node
                next_node.back_node.front_node = next_node.front_node
                next_node = None
        else:
            if next_node.back_node == None:
                flag = False
            else:
                next_node = next_node.back_node
    return first_node


def deleteFirst(first_node):
    if first_node.back_node == None:
        first_node = None
    else:
        first_node.back_node.front_node = None
        first_node = first_node.back_node
    return first_node

def deleteLast(first_node):
    flag = True
    check_node = first_node
    while flag:
        if check_node.back_node == None:
            if check_node.front_node == None:
                first_node = None
            else:
                check_node.front_node.back_node = None
                check_node = None
            flag = False
                #first_nodeをNoneにする
        else:
            check_node = check_node.back_node
    return first_node






n = int(input())
first_node = None
for i in range(n):
    tmp = input().split(" ")
    if tmp[0] == "insert":
        first_node = insert(int(tmp[1]),first_node)
    elif tmp[0] == "delete":
        first_node = delete(int(tmp[1]),first_node)
    elif tmp[0] == "deleteFirst":
        first_node = deleteFirst(first_node)
    elif tmp[0] == "deleteLast":
        first_node = deleteLast(first_node)

chk_node = first_node
answer = []
final_flag = True
while final_flag:
    if chk_node.back_node == None:
        final_flag = False
    answer.append(chk_node.value)
    chk_node = chk_node.back_node


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

Submission status: Time Limit Exceeded

Solution code:
class Node():
    def __init__(self,value,prv,nxt):
        self.value = value
        self.prv = prv
        self.nxt = nxt

class LinkedList():

    def __init__(self,head,tail):
        self.head = head
        self.tail = tail

    def insert(self,value):
        if self.head == None:
            self.head = Node(value,None,None)
            self.tail = self.head
        else:
            node = Node(value,None,self.head)
            if self.head.nxt == self.tail: #when only one node exists.
                self.head.prv = node
                self.head = node
            else:
                self.head.prv = node
                self.head = node

    def delete(self,value):
        check_node = self.head
        while not check_node == None:
            if check_node.value == value:
                if check_node == self.tail:
                    self.deleteLast()
                elif check_node == self.head:
                    self.head = check_node.nxt
                    check_node.nxt.prv = None
                else:
                    check_node.prv.nxt = check_node.nxt
                    check_node.nxt.prv = check_node.prv
                break
            check_node = check_node.nxt

    def deleteFirst(self):
        if self.head.nxt == None:
            self.head == None
        else:
            self.head = self.head.nxt

    def deleteLast(self):
        if self.head == self.tail:
            self.head = None
            self.tail = None
        else:
            self.tail.prv.nxt = None
            self.tail = self.tail.prv

n = int(input())
linkedList = LinkedList(None,None)

def getAnswer(linkedList):
    answer = []
    check = linkedList.head
    while True:
        answer.append(check.value)
        if check.nxt == None:
            break
        else:
            check = check.nxt

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

for _ in range(n):
    line = input()
    #print(line)
    if not line == "deleteFirst" and not line == "deleteLast":
        command = line.split(" ")[0]
        value = int(line.split(" ")[1])
    else:
        command = line

    if command == "insert":
        linkedList.insert(value)
    elif command == "delete":
        linkedList.delete(value)
    elif command == "deleteFirst":
        linkedList.deleteFirst()
    elif command == "deleteLast":
        linkedList.deleteLast()

    #getAnswer(linkedList)

getAnswer(linkedList)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())

q = deque()

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

	if com == "insert":
		q.appendleft(int(num[0]))
	elif com == "delete":
		if q.count(int(num[0])) != 0:
			q.remove(int(num[0]))
	elif com == "deleteFirst":
		q.popleft()
	elif com == "deleteLast":
		q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())

q = deque()

list2 = [input().split(" ") for _ in range(n)]

for lst in list2:

	if lst[0] == "insert":
		q.appendleft(int(lst[1]))
	elif lst[0] == "delete":
		if q.count(int(lst[1])) != 0:
			q.remove(int(lst[1]))
	elif lst[0] == "deleteFirst":
		q.popleft()
	elif lst[0] == "deleteLast":
		q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())

q = deque()

list2 = [input().split(" ") for _ in range(n)]

for lst in list2:

	if lst[0] == "insert":
		q.appendleft(int(lst[1]))
	elif lst[0] == "delete":
		try:
			q.remove(int(lst[1]))
		except:
			pass

	elif lst[0] == "deleteFirst":
		q.popleft()
	elif lst[0] == "deleteLast":
		q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())

q = deque()

for _ in range(n):
	com,*num = input().split(" ")
	if com == "insert":
		q.appendleft(num[0])
	elif com == "delete":
		try:
			q.remove(num[0])
		except:
			pass

	elif com == "deleteFirst":
		q.popleft()
	elif com == "deleteLast":
		q.pop()

print(*q)

Submission status: Time Limit Exceeded

Solution code:
import time

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

class MyDLL:
    def __init__(self):
        self.linkedlist = []
        self.length = 0
    
    def isEmpty(self):
        if self.length==0:
            return True
        return False
    
    def insert(self, x):
        # 連結リストの先頭にキー x を持つ要素を継ぎ足す。
        if self.isEmpty():
            # 連結リストが空の時
            new = Node(x, None, None)
            self.linkedlist.insert(0, new)         
        else:
            # 連結リストが空ではない時
            old = self.linkedlist[0] # 今まで先頭にいたノード
            new = Node(x, None, old) # 新しく先頭になるノード
            old.prev = new           # 今まで先頭にいたノードの前に新しいノードを登録
            self.linkedlist.insert(0, new)
        self.length += 1 # 連結リストの長さを更新

    def delete(self, x):
        # キー x を持つ最初の要素を連結リストから削除する。そのような要素が存在しない場合は何もしない。
        for node in self.linkedlist:
            if node.key==x:# キー x を持つ最初の要素    
                if node.prev is None:# 先頭だった時
                    node.next.prev = None # 次の要素の前の要素をNoneにする
                elif node.next is None:# 最後尾だった時
                    node.prev.next = None
                else:# 途中だった時
                    prev_node = node.prev
                    next_node = node.next
                    prev_node.next = next_node
                    next_node.prev = prev_node
                self.linkedlist.remove(node)# listから削除 
                self.length -= 1     
                break # キーxを持つ最初だけで良いのでbreak
        
    def deleteFirst(self):
        # リストの先頭の要素を削除する。
        if not self.isEmpty():
            first = self.linkedlist.pop(0)
            if self.length>1:
                first.next.prev = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def deleteLast(self):
        # リストの末尾の要素を削除する。        
        if not self.isEmpty():
            last = self.linkedlist.pop()
            if self.length>1:
                last.prev.next = None
            self.length -= 1 
        else:
            print("List is empty")
        


def main():
    n = int(input())
    commands = (input().split() for i in range(n))
    commands = ({'order': c[0], 'value': c[1]} if len(c)==2 else {'order': c[0]} for c in commands)
    dll = MyDLL()
    for c in commands:        
        if c['order']=='insert':
            dll.insert(c['value'])
        elif c['order']=='delete':
            dll.delete(c['value'])
        elif c['order']=='deleteFirst':
            dll.deleteFirst()
        elif c['order']=='deleteLast':
            dll.deleteLast()
        else:
            print("the command dont't exist")
    print(' '.join([node.key for node in dll.linkedlist]))


if __name__=='__main__':
    # start = time.time()
    main()
    # elapsed_time = time.time() - start
    # print ("elapsed_time:{0}".format(elapsed_time) + "[sec]")

Submission status: Time Limit Exceeded

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

class MyDLL:
    def __init__(self):
        self.linkedlist = []
        self.length = 0
    
    def isEmpty(self):
        if self.length==0:
            return True
        return False
    
    def insert(self, x):
        # 連結リストの先頭にキー x を持つ要素を継ぎ足す。
        if self.isEmpty():
            # 連結リストが空の時
            new = Node(x, None, None)            
        else:
            # 連結リストが空ではない時
            old = self.linkedlist[0] # 今まで先頭にいたノード
            new = Node(x, None, old) # 新しく先頭になるノード
            old.prev = new           # 今まで先頭にいたノードの前に新しいノードを登録
        self.linkedlist.insert(0, new)
        self.length += 1 # 連結リストの長さを更新

    def delete(self, x):
        # キー x を持つ最初の要素を連結リストから削除する。そのような要素が存在しない場合は何もしない。
        for node in self.linkedlist:
            if node.key==x:# キー x を持つ最初の要素    
                if node.prev is None:# 先頭だった時
                    node.next.prev = None # 次の要素の前の要素をNoneにする
                elif node.next is None:# 最後尾だった時
                    node.prev.next = None
                else:# 途中だった時
                    prev_node = node.prev
                    next_node = node.next
                    prev_node.next = next_node
                    next_node.prev = prev_node
                self.linkedlist.remove(node)# listから削除 
                self.length -= 1     
                break # キーxを持つ最初だけで良いのでbreak
        
    def deleteFirst(self):
        # リストの先頭の要素を削除する。
        if not self.isEmpty():
            first = self.linkedlist.pop(0)
            if self.length>1:
                first.next.prev = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def deleteLast(self):
        # リストの末尾の要素を削除する。        
        if not self.isEmpty():
            last = self.linkedlist.pop()
            if self.length>1:
                last.prev.next = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def print(self):
        if not self.isEmpty():
            print(' '.join([node.key for node in self.linkedlist]))
        else:
            print('')

def main():
    n = int(input())
    commands = (input() for i in range(n)) # generator式リスト内包表記
    # commands = ({'order': c[0], 'value': c[1]} if len(c)==2 else {'order': c[0]} for c in commands)
    dll = MyDLL()
    for c in commands:
        if 'insert' in c:
            dll.insert(c.split()[1])
        elif 'deleteFirst' in c:
            dll.deleteFirst()
        elif 'deleteLast' in c:
            dll.deleteLast()
        elif 'delete' in c:
            dll.delete(c.split()[1])
        else:
            print("the command dont't exist")
            print(c)
    dll.print()    


if __name__=='__main__':    
    main()

Submission status: Time Limit Exceeded

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

class MyDLL:
    def __init__(self):
        self.linkedlist = []
        self.length = 0
    
    def isEmpty(self):
        if self.length==0:
            return True
        return False
    
    def insert(self, x):
        # 連結リストの先頭にキー x を持つ要素を継ぎ足す。
        if self.length==0:
            # 連結リストが空の時
            new = Node(x, None, None)            
        else:
            # 連結リストが空ではない時
            old = self.linkedlist[0] # 今まで先頭にいたノード
            new = Node(x, None, old) # 新しく先頭になるノード
            old.prev = new           # 今まで先頭にいたノードの前に新しいノードを登録
        self.linkedlist.insert(0, new)
        self.length += 1 # 連結リストの長さを更新

    def delete(self, x):
        # キー x を持つ最初の要素を連結リストから削除する。そのような要素が存在しない場合は何もしない。
        for node in self.linkedlist:
            if node.key==x:# キー x を持つ最初の要素    
                if node.prev is None:# 先頭だった時
                    node.next.prev = None # 次の要素の前の要素をNoneにする
                elif node.next is None:# 最後尾だった時
                    node.prev.next = None
                else:# 途中だった時
                    prev_node = node.prev
                    next_node = node.next
                    prev_node.next = next_node
                    next_node.prev = prev_node
                self.linkedlist.remove(node)# listから削除 
                self.length -= 1     
                break # キーxを持つ最初だけで良いのでbreak
        
    def deleteFirst(self):
        # リストの先頭の要素を削除する。
        if not self.length==0:
            first = self.linkedlist.pop(0)
            if self.length>1:
                first.next.prev = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def deleteLast(self):
        # リストの末尾の要素を削除する。        
        if not self.length==0:
            last = self.linkedlist.pop()
            if self.length>1:
                last.prev.next = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def print(self):
        if not self.length==0:
            print(' '.join([node.key for node in self.linkedlist]))
        else:
            print('')

def main():   
    n = int(input())
    commands = (input() for i in range(n)) # generator式リスト内包表記
    dll = MyDLL()
    for c in commands:
        if 'insert' in c:
            dll.insert(c.split()[1])
        elif 'deleteFirst' in c:
            dll.deleteFirst()
        elif 'deleteLast' in c:
            dll.deleteLast()
        elif 'delete' in c:
            dll.delete(c.split()[1])
        else:
            print("the command dont't exist")
            print(c)
    dll.print()    
main()

Submission status: Time Limit Exceeded

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

class MyDLL:
    def __init__(self):
        self.linkedlist = []
        self.length = 0
    
    def insert(self, x):
        # 連結リストの先頭にキー x を持つ要素を継ぎ足す。
        if self.length==0:
            # 連結リストが空の時
            new = Node(x, None, None)            
        else:
            # 連結リストが空ではない時
            old = self.linkedlist[0] # 今まで先頭にいたノード
            new = Node(x, None, old) # 新しく先頭になるノード
            old.prev = new           # 今まで先頭にいたノードの前に新しいノードを登録
        self.linkedlist.insert(0, new)
        self.length += 1 # 連結リストの長さを更新

    def delete(self, x):
        # キー x を持つ最初の要素を連結リストから削除する。そのような要素が存在しない場合は何もしない。
        for node in self.linkedlist:
            if node.key==x:# キー x を持つ最初の要素    
                if node.prev is None:# 先頭だった時
                    node.next.prev = None # 次の要素の前の要素をNoneにする
                elif node.next is None:# 最後尾だった時
                    node.prev.next = None
                else:# 途中だった時
                    prev_node = node.prev
                    next_node = node.next
                    prev_node.next = next_node
                    next_node.prev = prev_node
                self.linkedlist.remove(node)# listから削除 
                self.length -= 1     
                break # キーxを持つ最初だけで良いのでbreak
        
    def deleteFirst(self):
        # リストの先頭の要素を削除する。
        if not self.length==0:
            first = self.linkedlist.pop(0)
            if self.length>1:
                first.next.prev = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def deleteLast(self):
        # リストの末尾の要素を削除する。        
        if not self.length==0:
            last = self.linkedlist.pop()
            if self.length>1:
                last.prev.next = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def print(self):
        if not self.length==0:
            print(' '.join([node.key for node in self.linkedlist]))
        else:
            print('')

def main():   
    n = int(input())
    commands = (input() for i in range(n)) # generator式リスト内包表記
    dll = MyDLL()
    for c in commands:
        if 'insert' in c:
            dll.insert(c.split()[1])
        elif 'deleteFirst' in c:
            dll.deleteFirst()
        elif 'deleteLast' in c:
            dll.deleteLast()
        elif 'delete' in c:
            dll.delete(c.split()[1])
        else:
            print("the command dont't exist")
            print(c)
    dll.print()    
main()

Submission status: Time Limit Exceeded

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

class MyDLL:
    def __init__(self):
        self.linkedlist = []
        self.length = 0
    
    def insert(self, x):
        # 連結リストの先頭にキー x を持つ要素を継ぎ足す。
        if self.length==0:
            # 連結リストが空の時
            new = Node(x, None, None)            
        else:
            # 連結リストが空ではない時
            old = self.linkedlist[0] # 今まで先頭にいたノード
            new = Node(x, None, old) # 新しく先頭になるノード
            old.prev = new           # 今まで先頭にいたノードの前に新しいノードを登録
        self.linkedlist.insert(0, new)
        self.length += 1 # 連結リストの長さを更新

    def delete(self, x):
        # キー x を持つ最初の要素を連結リストから削除する。そのような要素が存在しない場合は何もしない。
        for node in self.linkedlist:
            if node.key==x:# キー x を持つ最初の要素    
                if node.prev is None:# 先頭だった時
                    node.next.prev = None # 次の要素の前の要素をNoneにする
                elif node.next is None:# 最後尾だった時
                    node.prev.next = None
                else:# 途中だった時
                    prev_node = node.prev
                    next_node = node.next
                    prev_node.next = next_node
                    next_node.prev = prev_node
                self.linkedlist.remove(node)# listから削除 
                self.length -= 1     
                break # キーxを持つ最初だけで良いのでbreak
        
    def deleteFirst(self):
        # リストの先頭の要素を削除する。
        if not self.length==0:
            first = self.linkedlist.pop(0)
            if self.length>1:
                first.next.prev = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def deleteLast(self):
        # リストの末尾の要素を削除する。        
        if not self.length==0:
            last = self.linkedlist.pop()
            if self.length>1:
                last.prev.next = None
            self.length -= 1 
        else:
            print("List is empty")
        
    def print(self):
        if not self.length==0:
            print(' '.join([node.key for node in self.linkedlist]))
        else:
            print('')

def main():
    n = int(input())
    commands = (input() for i in range(n)) # generator式リスト内包表記
    dll = MyDLL()
    for c in commands:
        if 'insert' in c:
            dll.insert(c.split()[1])
        elif 'First' in c:
            dll.deleteFirst()
        elif 'Last' in c:
            dll.deleteLast()
        elif 'delete' in c:
            dll.delete(c.split()[1])
        else:
            print("the command dont't exist")
            print(c)
    dll.print()
main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
commands = [input().split() for _ in range(n)]

l = []
for com in commands:
    if com[0]=='insert':
        l.insert(0, com[1])
    elif com[0]=='delete':
        try:
            l.remove(com[1])
        except:
            pass
    elif com[0]=='deleteFirst':
        l.pop(0)
    elif com[0]=='deleteLast':
        l.pop()
s = ' '.join(l)
print(s)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
commands = [input().split() for _ in range(n)]

l = deque([])
for com in commands:
    if com[0]=='insert':
        l.insert(0, com[1])
    elif com[0]=='delete':
        try:
            l.remove(com[1])
        except:
            pass
    elif com[0]=='deleteFirst':
        l.popleft()
    elif com[0]=='deleteLast':
        l.pop()
s = ' '.join(l)
print(s)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
commands = [input().split() for _ in range(n)]

l = deque([])
for com in commands:
    if com[0]=='insert':
        l.appendleft(com[1])
    elif com[0]=='delete':
        try:
            l.remove(com[1])
        except:
            pass
    elif com[0]=='deleteFirst':
        l.popleft()
    elif com[0]=='deleteLast':
        l.pop()
s = ' '.join(l)
print(s)