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:
class DoubleEndedList:
# クラス内クラスを作る(CellクラスはDoubleEndedListクラスからしか参照しないため)
    class Cell:
        def __init__(self, data, prv = None, nxt = None):
            self.data = data
            self.prv = prv
            self.nxt = nxt

    def __init__(self):
        head = DoubleEndedList.Cell(None)
        head.prv = head
        head.nxt = head
        self.head = head

    def insertFirst(self, data):
        x = DoubleEndedList.Cell(data, self.head, self.head.nxt)
        self.head.nxt = x
        x.nxt.prv = x

    def delete(self, index):
        x = self.head.nxt
        while x is not self.head:
            if x.data == index:
                break
            x = x.nxt
        # indexと一致するdataが見つからなかった時
        if x is self.head:
            return
        x.prv.nxt = x.nxt
        x.nxt.prv = x.prv

    def deleteFirst(self):
        x = self.head.nxt
        x.prv.nxt = x.nxt
        x.nxt.prv = x.prv

    def deleteLast(self):
        x = self.head.prv
        x.prv.nxt = x.nxt
        x.nxt.prv = x.prv
deque = DoubleEndedList()
for i in range(int(input())):
    cmd = input().split()
    if cmd[0] == "insert":
        deque.insertFirst(int(cmd[1]))
    elif cmd[0] == "delete":
        deque.delete(int(cmd[1]))
    elif cmd[0] == "deleteFirst":
        deque.deleteFirst()
    elif cmd[0] == "deleteLast":
        deque.deleteLast()
    else:
        print("Wrong Command")

n = deque.head.nxt
while n is not deque.head:
    print(n.data, end = "")
    if n.nxt is not deque.head:
        print(" ", end = "")
    else:
        print("")
    n = n.nxt

Submission status: Time Limit Exceeded

Solution code:

import sys
#import numpy as np
import copy

N = int(input())
list = []

for i in range(N):
    # insert, delete, deleteFirst, deleteLast
    line = input().rstrip().split(' ')
    if line[0]=='insert':
        #list.append((int)(line[1]))
        list.insert(0, (int)(line[1]))
    elif line[0]=='delete':
        for j in range(len(list)):
            if list[j]==(int)(line[1]):
                list.pop(j)
                break
    elif line[0]=='deleteFirst':
        list.pop(0)
    elif line[0]=='deleteLast':
        list.pop(len(list)-1)

for i in range(len(list)):
    print( (str)(list[i]), end="")
    if i != len(list)-1:
        print(" ",end="")
print()

Submission status: Time Limit Exceeded

Solution code:

import sys
#import numpy as np
from collections import deque
#import collections

N = int(input())


list = deque()

for i in range(N):
    # insert, delete, deleteFirst, deleteLast
    line = input().rstrip().split(' ')
    if line[0]=='insert':
        #list.append((int)(line[1]))
        list.appendleft((int)(line[1]))
    elif line[0]=='delete':
        try:
            list.remove((int)(line[1]))
        except ValueError:
            pass
    elif line[0]=='deleteFirst':
        list.popleft()
    elif line[0]=='deleteLast':
        list.pop()

for i in range(len(list)):
    print( (str)(list[i]), end="")
    if i != len(list)-1:
        print(" ",end="")
print()


u"""
list = []

for i in range(N):
    # insert, delete, deleteFirst, deleteLast
    line = input().rstrip().split(' ')
    if line[0]=='insert':
        #list.append((int)(line[1]))
        list.insert(0, (int)(line[1]))
    elif line[0]=='delete':
        for j in range(len(list)):
            if list[j]==(int)(line[1]):
                list.pop(j)
                break
    elif line[0]=='deleteFirst':
        list.pop(0)
    elif line[0]=='deleteLast':
        list.pop(len(list)-1)

for i in range(len(list)):
    print( (str)(list[i]), end="")
    if i != len(list)-1:
        print(" ",end="")
print()
"""

Submission status: Time Limit Exceeded

Solution code:

import sys
#import numpy as np
from collections import deque
#import collections

N = int(input())


list = deque()

for i in range(N):
    # insert, delete, deleteFirst, deleteLast
    line = input().rstrip().split(' ')
    if line[0][0]=='i':
        #list.append((int)(line[1]))
        list.appendleft((int)(line[1]))
    else:
        if len(line[0])<7:
            try:
                list.remove((int)(line[1]))
            except ValueError:
                pass
        elif line[0][6]=='F':
            list.popleft()
        elif line[0][6]=='L':
            list.pop()

for i in range(len(list)):
    print( (str)(list[i]), end="")
    if i != len(list)-1:
        print(" ",end="")
print()


u"""
list = []

for i in range(N):
    # insert, delete, deleteFirst, deleteLast
    line = input().rstrip().split(' ')
    if line[0]=='insert':
        #list.append((int)(line[1]))
        list.insert(0, (int)(line[1]))
    elif line[0]=='delete':
        for j in range(len(list)):
            if list[j]==(int)(line[1]):
                list.pop(j)
                break
    elif line[0]=='deleteFirst':
        list.pop(0)
    elif line[0]=='deleteLast':
        list.pop(len(list)-1)

for i in range(len(list)):
    print( (str)(list[i]), end="")
    if i != len(list)-1:
        print(" ",end="")
print()
"""

Submission status: Time Limit Exceeded

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

class link():
    def __init__(self):
        self.node = Node(None)
        self.node.prev = self.node.next = self.node

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

    def search(self, key):
        elem = self.node.next
        while (elem != self.node) and (elem.key != key):
            elem = elem.next
        return elem

    def delete(self, node):
        if node == self.node:
            return None
        node.prev.next = node.next
        node.next.prev = node.prev

    def deleteFirst(self):
        self.delete(self.node.next)

    def deleteLast(self):
        self.delete(self.node.prev)

    def show_keys(self):
        keys = []
        elem = self.node.next
        while elem != self.node:
            keys.append(str(elem.key))
            elem = elem.next
        print(' '.join(keys))

n = int(input())
linkedlist = link()
for i in range(n):
    com = input().split()
    if com[0] == 'insert':
        linkedlist.insert(int(com[1]))
    elif com[0] == 'delete':
        linkedlist.delete(linkedlist.search(int(com[1])))
    elif com[0] == 'deleteFirst':
        linkedlist.deleteFirst()
    else:
        linkedlist.deleteLast()
linkedlist.show_keys()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

Submission status: Time Limit Exceeded

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

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

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

    def delete(self, node):
        if node is not None:
            if node in (self.head, self.tail):
                return
            else:
                node.prev.next, node.next.prev = node.next, node.prev
                node = None

    def delete_first(self):
        self.delete(self.head.next)

    def delete_last(self):
        self.delete(self.tail.prev)

    def delete_first_value(self, v):
        self.delete(self.find(v, self.head))

    def find(self, v, cur=None):
        if cur is None:
            cur = self.head

        while cur != self.tail:
            cur = cur.next
            if cur.value == v:
                return cur

        return None

    def __str__(self):
        cur = self.head.next
        vs = []
        while cur != self.tail:
            vs.append(str(cur.value))
            cur = cur.next

        return " ".join(vs)


def run():
    steps = int(input())
    dl = DoubleLinkedList()

    for _ in range(steps): # flake8: noqa
        command = input()
        if command.startswith('insert'):
            c, v = command.split()
            dl.insert(v)
        elif command.startswith('deleteFirst'):
            dl.delete_first()
        elif command.startswith('deleteLast'):
            dl.delete_last()
        elif command.startswith('delete'):
            c, v = command.split()
            dl.delete_first_value(v)
        else:
            raise ValueError()

    print(dl)


if __name__ == '__main__':
    run()

Submission status: Time Limit Exceeded

Solution code:
l = []
for _ in range(int(input())):
  a = input().split()
  if "insert" in a: l.insert(0, int(a[1]))
  elif "deleteFirst" in a: l.pop(0)
  elif "deleteLast" in a: l.pop()
  else:
    if int(a[1]) in l: l.remove(int(a[1]))
print(*l)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
d = deque()
for _ in range(int(input())):
  a = input().split()
  if "insert" in a: d.appendleft(int(a[1]))
  elif "deleteFirst" in a: d.popleft()
  elif "deleteLast" in a: d.pop()
  else:
    try: d.remove(int(a[1]))
    except: pass
print(*d)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
commands = []
for a in range(n):
    raw = input().split()
    try:
        commands.append([raw[0], int(raw[1])])
    except:
        commands.append([raw[0], 'none'])

result = []
for a in commands:
    command, x = a[0], a[1]
    if command == 'insert':
        result.append(x)
    elif command == 'delete':
        if x in result:
            result.reverse()
            result.remove(x)
            result.reverse()
        else:
            continue
    elif command == 'deleteFirst':
        del result[-1]
    else:
        del result[0]

result.reverse()
print(*result)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
commands = []
for a in range(n):
    raw = input().split()
    try:
        commands.append([raw[0], int(raw[1])])
    except:
        commands.append([raw[0], 'none'])

result = []
for a in commands:
    command, x = a[0], a[1]
    if command == 'insert':
        result.append(x)
    elif command == 'delete':
        if x in result:
            if result.count(x) == 1:
                result.remove(x)
            else:
                for i in range(len(result)-1, -1, -1):
                    if result[i] == x:
                        del result[i]
                        break
        else:
            continue
    elif command == 'deleteFirst':
        del result[-1]
    else:
        del result[0]

for i in range(len(result)-1, -1, -1):
    if i == 0:
        print(result[i])
    else:
        print(result[i], end=' ')

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
result = []
for a in range(n):
    c = input().split()
    if c[0] == 'insert':
        result.append(int(c[1]))
    elif c[0] == 'delete':
        c[1] = int(c[1])
        if c[1] in result:
            if result.count(c[1]) == 1:
                result.remove(c[1])
            else:
                for i in range(len(result)-1, -1, -1):
                    if result[i] == c[1]:
                        del result[i]
                        break
        else:
            continue
    elif c[0] == 'deleteFirst':
        del result[-1]
    else:
        del result[0]

for i in range(len(result)-1, -1, -1):
    if i == 0:
        print(result[i])
    else:
        print(result[i], end=' ')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
result = deque()
func = {'insert':result.appendleft,\
        'delete':result.remove,\
        'deleteFirst':result.popleft,\
        'deleteLast':result.pop}

for i in range(n):
    c = input().split()
    if len(c) > 1:
        try:
            func[c[0]](int(c[1]))
        except:
            continue
    else:
        func[c[0]]()

print(*result)

Submission status: Time Limit Exceeded

Solution code:
#課題3-C 16D8102014J 井口和人　4/27
#python
from collections import deque
n = int(input())
a = deque()
for i in range(n):
    s = input().split(" ")
    if s[0] == "insert":
        a.appendleft(int(s[1]))
    elif s[0] == "delete":
        if int(s[1]) in a:
            a.remove(int(s[1]))
    elif s[0] == "deleteLast":
        a.pop()
    elif s[0] == "deleteFirst":
        a.popleft()
b = list(a)
for i in range(len(b)):
    if i == len(b)-1:
        print(b[i])
    else:
        print(b[i],end=" ")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
a = deque()
for i in range(n):
    s = input().split(" ")
    if s[0] == "insert":
        a.appendleft(int(s[1]))
    elif s[0] == "delete":
        if int(s[1]) in a:
            a.remove(int(s[1]))
    elif s[0] == "deleteLast":
        a.pop()
    elif s[0] == "deleteFirst":
        a.popleft()
b = list(a)
for i in range(len(b)):
    if i == len(b)-1:
        print(b[i])
    else:
        print(b[i],end=" ")

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = []
for i in range(n):
    c = input()
    if c == "deleteFirst":
        a.pop(0)
    elif c == "deleteLast":
        a.pop()
    else:
        c, v = c.split()
        v = int(v)
        if c == "insert":
            a.insert(0, v)
        elif v in a:
            a.remove(v)
print(" ".join(map(str, a)))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
for i in range(n):
    s = input().split()
    if len(s) == 2:
        key = s[1]
    com = s[0]
         
    if com == 'insert':
        a.insert(0, key)
    elif com == 'delete':
        try:
            a.remove(key)
        except ValueError:
            pass
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
for i in range(n):
    s = input().split()
    if len(s) == 2:
        key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        a.insert(0, key)
    elif com == 'delete':
        try:
            a.remove(key)
        except ValueError:
            pass
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
for i in range(n):
    s = input().split()
    if len(s) == 2:
        key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
from sys import stdin

def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
#for cmd in sys.stdin.readlines():
for i in range(n):
    s = stdin.readline().split()
    #s = input().split()
    if len(s) == 2:
        key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
from sys import stdin

def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
sin = stdin.readlines()
for i in range(n):
    s = sin[i].split()
    #s = input().split()
    if len(s) == 2:
        key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
from sys import stdin

def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    print(ans)

a = []
n = int(input())
s_in = stdin.readlines()
for i in range(n):
    s = s_in[i].split()
    #s = input().split()
    #if len(s) == 2:
    #    key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        key = int(s[1])
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        key = int(s[1])
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
import sys

def print_array(g):
    ans = str(g[0])
    if len(g) > 1:
        for i in range(1,len(g)):
            ans += ' '+str(g[i]) 
    ans += '\n'
    sys.stdout.write(ans)

a = []
n = int(input())
s_in = sys.stdin.readlines()
for i in range(n):
    s = s_in[i].split()
    #s = input().split()
    #if len(s) == 2:
    #    key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        key = int(s[1])
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        key = int(s[1])
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 18:31:35 2018
ALDS1-3c simple implementation owing to the feature of python.
@author: maezawa
"""
import sys

def print_array(g):
    sys.stdout.write(str(g[0]))
    if len(g) > 1:
        for i in range(1,len(g)):
            sys.stdout.write(' '+str(g[i])) 
    sys.stdout.write('\n')

a = []
n = int(input())
s_in = sys.stdin.readlines()
for i in range(n):
    s = s_in[i].split()
    #s = input().split()
    #if len(s) == 2:
    #    key = int(s[1])
    com = s[0]
         
    if com == 'insert':
        key = int(s[1])
        a.insert(0, key)
    elif com == 'deleteFirst':
        a.pop(0)
    elif com == 'deleteLast':
        a.pop(-1)
    elif com == 'delete':
        key = int(s[1])
        try:
            a.remove(key)
        except ValueError:
            pass

print_array(a)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
dll=[]

for i in range(n):
    line=input()
    d=line.split(" ")
    if d[0]=="insert":
        dll=[int(d[1])]+dll

    elif d[0]=="delete":
        if int(d[1]) not in dll:
            continue
        ind=dll.index(int(d[1]))
        dll.pop(ind)

    elif d[0]=="deleteFirst":
        dll.pop(0)
    elif d[0]=="deleteLast":
        dll.pop()

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

Submission status: Time Limit Exceeded

Solution code:
#! python3
# doubly_linked_list.py

keys = []

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

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

Submission status: Time Limit Exceeded

Solution code:

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

n = int(input())
a = []
for i in range(n):
    x = input().split()
    if x[0] == "insert":
        a.insert(0,int(x[1]))
    elif x[0] == "delete":
        if int(x[1]) in a:
            a.remove(int(x[1]))
    elif x[0] == "deleteFirst":
        a.pop(0)
    elif x[0] == "deleteLast":
        a.pop()

pr(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
d = deque()
for _ in range(n):
    x = input().split()
    if x[0][0] == 'i':
        d.appendleft(int(x[1]))
    elif x[0] == 'delete':
        try:
            d.remove(int(x[1]))
        except ValueError:
            pass
    elif x[0][6] == 'F':
        d.popleft()
    else:
        d.pop()
print(*d)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
d = deque()
n = int(input())
for i in range(n):
    s = input().split()
    if str(s[0]) == 'insert': d.appendleft(int(s[1]))
    elif str(s[0]) =='delete': 
        if int(s[1]) in d:
            d.remove(int(s[1]))
        else: pass
    elif str(s[0]) =='deleteFirst': d.popleft()
    else: d.pop()

print(*d)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
d = deque()
n = int(input())
for i in range(n):
    s = input().split()
    if str(s[0][0]) == 'i': d.appendleft(int(s[1]))
    elif str(s[0]) =='delete': 
        if int(s[1]) in d:
            d.remove(int(s[1]))
        else: pass
    elif str(s[0][6]) =='F': d.popleft()
    else: d.pop()

print(*d)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
array=[]
for i in range(n):
	a=input()
	
	if a=="deleteFirst":
		array.pop(0)
	elif a=="deleteLast":
		array.pop()
	else:
		command,x=a.split()
		if command=="insert":
			array.insert(0,x)
		elif command=="delete":
			if (x in array):
				array.remove(x)
				
print(" ".join(array))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
array=[]
for i in range(n):
	a=input()
	
	if a=="deleteFirst":
		array.pop(0)
	elif a=="deleteLast":
		array.pop()
	else:
		command,x=a.split()
		x=int(x)
		if command=="insert":
			array.insert(0,x)
		elif command=="delete":
			if (x in array):
				array.remove(x)
				
print(" ".join(map(str,array)))

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 LinkedList:
    def __init__(self):
        self.nil = Node(None, None, None)
        self.nil.prev = self.nil
        self.nil.next = self.nil

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

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

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

        return cur

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

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

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

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

    def delete_key(self, key):
        node = self.search(key)
        self.delete_node(node)


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

    for i in range(n):
        order = input().split()

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

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

    print()


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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(self, key):
        node = Node(key, self.nil, self.nil.next)
        self.nil.next.prev = node
        self.nil.next = node

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

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

        return cur

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

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

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

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

    def delete_key(self, key):
        node = self.search(key)
        self.delete_node(node)


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

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

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

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

Solution code:
n = int(input())
L = []

for i in range(n):
    com = input()
    if com == "deleteFirst":
        del L[0]
    elif com == "deleteLast":
        del L[len(L)-1]
    else:
        c = com.split()
        if c[0] == "insert":
            L.insert(0, int(c[1]))
        elif c[0] == "delete":
            for i in range(len(L)):
                if L[i] == int(c[1]):
                    del L[i]
                    break
    #print(L)
        
for i in range(len(L)):
    if i == len(L)-1:
        print(L[i])
    else:
        print(L[i], end=' ')

Submission status: Time Limit Exceeded

Solution code:
class DLL:
    class Node:
        def __init__(self, x, y, z):
            self.v = x
            self.prv = y
            self.nxt = z

    def __init__(self):
        init = DLL.Node(None, None, None)
        init.prv = init
        init.nxt = init
        self.size = 0
        self.init = init

    def insert(self, x):
        i = self.init
        j = i.nxt
        k = DLL.Node(x, i, j)
        i.nxt = k
        j.prv = k
        self.size += 1

    def deleteFirst(self):
        if self.size != 0:
            i = self.init
            k = i.nxt
            j = k.nxt
            i.nxt = j
            j.prv = i
            self.size -= 1

    def deleteLast(self):
        if self.size != 0:
            i = self.init
            k = i.prv
            j = k.prv
            i.prv = j
            j.nxt = i
            self.size -= 1

    def delete(self, x):
        if self.size != 0:
            i = self.init
            k = i.nxt
            while 1:
                if k.v == x:
                    i = k.prv
                    j = k.nxt
                    i.nxt = j
                    j.prv = i
                    self.size -= 1
                    break
                else:
                    k = k.nxt

    def prt(self):
        f = self.init
        s = f.nxt
        l = f.prv
        while 1:
            if s != l:
                print(s.v, end=' ')
                s = s.nxt
            else:
                print(l.v)
                break

n = int(input())
L = DLL()

for i in range(n):
    com = input()
    if com == "deleteFirst":
        L.deleteFirst()
    elif com == "deleteLast":
        L.deleteLast()
    else:
        C = com.split()
        if C[0] == "insert":
            L.insert(int(C[1]))
        elif C[0] == "delete":
            L.delete(int(C[1]))
    #L.prt()
    
L.prt()