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:
# -*- coding: utf-8 -*-

commands = {"insert": lambda x, l: insert(x, l),
            "delete": lambda x, l: delete(x, l),
            "deleteFirst": lambda x, l: deleteFirst(x, l),
            "deleteLast": lambda x, l: deleteLast(x, l)}


# ??£??????????????????????????????x?????????????´?????¶?????¶????
def insert(x, l):
    l = [x] + l
    return l


# ??????x??????????????????????´??????£??????????????????????????????
def delete(x, l):
    for i in xrange(len(l)):
        if l[i] == x:
            l.pop(i)
            break
    return l


# ?????????????????????????´????????????????
def deleteFirst(x, l):
    l.pop(0)
    return l


# ????????????????°????????´????????????????
def deleteLast(x, l):
    l.pop()
    return l


if __name__ == '__main__':
    N = input()
    functions, args = [], []
    for i in xrange(N):
        command = raw_input().split()
        functions.append(command[0])
        if command[0] == "deleteFirst" or command[0] == "deleteLast":
            args.append(0)
        else:
            args.append(int(command[1]))

    result = []
    for i in xrange(len(functions)):
        result = commands[functions[i]](args[i], result)
    print ' '.join(map(str, result))

Submission status: Time Limit Exceeded

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

functions = {"insert": lambda x, l: insert(x, l),
             "delete": lambda x, l: delete(x, l),
             "deleteFirst": lambda x, l: deleteFirst(x, l),
             "deleteLast": lambda x, l: deleteLast(x, l)}


# ??£??????????????????????????????x?????????????´?????¶?????¶????
def insert(x, l):
    l = [x] + l
    return l


# ??????x??????????????????????´??????£??????????????????????????????
def delete(x, l):
    for i in xrange(len(l)):
        if l[i] == x:
            l.pop(i)
            break
    return l


# ?????????????????????????´????????????????
def deleteFirst(x, l):
    l.pop(0)
    return l


# ????????????????°????????´????????????????
def deleteLast(x, l):
    l.pop()
    return l


if __name__ == '__main__':
    N = input()
    commands, args = [], []
    column = [raw_input().split() for i in xrange(N)]

    for i in xrange(N):
        # command = raw_input().split()
        commands.append(column[i][0])
        if column[i][0] == "deleteFirst" or column[i][0] == "deleteLast":
            args.append(0)
        else:
            args.append(int(column[i][1]))

    result = []
    for i in xrange(len(commands)):
        result = functions[commands[i]](args[i], result)
    print ' '.join(map(str, result))

Submission status: Time Limit Exceeded

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_C&lang=jp
sample_input = list(range(3))
sample_input[0] = '''7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5'''
sample_input[1] = '''9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast'''
sample_input[2] = '''8
insert 1000000000
insert 999999999
deleteLast
insert 1234566890
insert 5
deleteFirst
insert 7
delete 5'''
give_sample_input = None
if give_sample_input is not None:
    sample_input_list = sample_input[give_sample_input].split('\n')
    def input():
        return sample_input_list.pop(0)
        
# main
class DoublyLinkedList():
    
    def __init__(self, a_data = []):
        self.data = a_data
    
    def insert(self, x):
        self.data.insert(0, x)
    
    def delete(self, x):
        try:
            self.data.remove(x)
        except ValueError:
            return
    
    def delete_first(self):
        self.data.pop(0)
    
    def delete_last(self):
        self.data.pop()

    def to_str(self):
        output = ''
        for x in self.data:
            output += str(x) + ' '
        output = output.rstrip()
        return output

num_of_command = int(input())
doublely_list = DoublyLinkedList()
for n in range(num_of_command):
    str_command = input()
    if str_command == 'deleteFirst':
        doublely_list.delete_first()
        continue
    elif str_command == 'deleteLast':
        doublely_list.delete_last()
        continue
    command_name = str_command.split()[0]
    command_obj = int(str_command.split()[1])
    if command_name == 'insert':
        doublely_list.insert(command_obj)
    elif command_name == 'delete':
        doublely_list.delete(command_obj)

print(doublely_list.to_str())

Submission status: Time Limit Exceeded

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_C&lang=jp
sample_input = list(range(3))
sample_input[0] = '''7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5'''
sample_input[1] = '''9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast'''
sample_input[2] = '''8
insert 1000000000
insert 999999999
deleteLast
insert 1234566890
insert 5
deleteFirst
insert 7
delete 5'''
give_sample_input = None
if give_sample_input is not None:
    sample_input_list = sample_input[give_sample_input].split('\n')
    def input():
        return sample_input_list.pop(0)
        
# main
class Node:
    
    def __init__(self, value, prev=None, next=None):
        self.value = value
        self.prev = prev
        self.next = next

class DoublyLinkedList:
    
    def __init__(self):
        self.be_empty()
    
    def be_empty(self):
        self.first = None
        self.last = None
        
    def is_empty(self):
        if self.first is None:
            assert self.last is None
            return True
        else: 
            return False
    
    def insert_node(self, node):
        if self.is_empty():
            self.first = node
            self.last = node
        else:
            self.first.prev = node
            node.next = self.first
            node.prev = None
            self.first = node
        
    def insert(self, x):
        self.insert_node(Node(x))
    
    def delete(self, x):
        '''Note : if x is not found, this does nothing'''
        if self.is_empty():
            return
        else:
            item = self.first
            while True:
                if item.value == x:
                    break
                else:
                    item = item.next
                    if item is None:
                        return
            if item is self.last:
                self.delete_last()
            elif item is self.first:
                self.delete_first()
            else:
                prev = item.prev
                next = item.next
                prev.next = next
                next.prev = prev
                
    
    def delete_first(self):
        if self.first is self.last:
            self.be_empty()
        else:
            second = self.first.next
            second.prev = None
            self.first = second
    
    def delete_last(self):
        if self.first is self.last:
            self.be_empty()
        else:
            second = self.last.prev
            second.next = None
            self.last = second

    def to_str(self):
        output = ''
        if self.is_empty():
            return output
        else:
            item = self.first
            while item is not None:
                output += str(item.value) + ' '
                item = item.next
            output = output.rstrip()
            return output


num_of_command = int(input())
doublely_list = DoublyLinkedList()
for n in range(num_of_command):
    str_command = input()
    if str_command == 'deleteFirst':
        doublely_list.delete_first()
        continue
    elif str_command == 'deleteLast':
        doublely_list.delete_last()
        continue
    command_name = str_command.split()[0]
    command_obj = int(str_command.split()[1])
    if command_name == 'insert':
        doublely_list.insert(command_obj)
    elif command_name == 'delete':
        doublely_list.delete(command_obj)

print(doublely_list.to_str())

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self, key, prevNode, nextNode):
        self.key = key
        self.prevNode = prevNode
        self.nextNode = nextNode

def deleteNode(node):
    if node == fNode:
        return
    node.prevNode.nextNode = node.nextNode
    node.nextNode.prevNode = node.prevNode

def searchNode(key):
    global fNode
    node = fNode.nextNode
    while node != fNode and node.key != key:
        node = node.nextNode
    return node

def searchLast():
    global fNode
    node = fNode.nextNode
    while node != fNode:
        prevNode = node
        node = node.nextNode
    return prevNode

def nodeList():
    global fNode
    node = fNode.nextNode
    keys = []
    while node != fNode:
        keys.append(node.key)
        node = node.nextNode

    print(" ".join(keys))

# ????????????????????????
fNode = Node(None, None, None)
fNode.prevNode = fNode
fNode.nextNode = fNode

n = int(input())

for i in range(0, n):
    inputs = input().split(' ')
    command = inputs.pop(0)
    if inputs:
        key = inputs.pop(0)

    if command == 'insert':
        insertNode = Node(key, fNode, fNode.nextNode)
        fNode.nextNode.prevNode = insertNode
        fNode.nextNode = insertNode
    if command == 'delete':
        deleteNode(searchNode(key))
    if command == 'deleteFirst':
        deleteNode(fNode.nextNode)
    if command == 'deleteLast':
        deleteNode(fNode.prevNode)
        #deleteNode(searchLast())
nodeList()

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self, key, prevNode, nextNode):
        self.key = key
        self.prevNode = prevNode
        self.nextNode = nextNode

def deleteNode(node):
    if node == fNode:
        return
    node.prevNode.nextNode = node.nextNode
    node.nextNode.prevNode = node.prevNode

def searchNode(key):
    global fNode
    node = fNode.nextNode
    while node != fNode and node.key != key:
        node = node.nextNode
    return node

'''
def searchLast():
    global fNode
    node = fNode.nextNode
    while node != fNode:
        prevNode = node
        node = node.nextNode
    return prevNode
'''

def nodeList():
    global fNode
    node = fNode.nextNode
    keys = []
    while node != fNode:
        keys.append(node.key)
        node = node.nextNode

    print(" ".join(keys))

# ????????????????????????
fNode = Node(None, None, None)
fNode.prevNode = fNode
fNode.nextNode = fNode

n = int(input())

for i in range(0, n):
    inputs = input().split(' ')
    command = inputs[0]

    if command == 'insert':
        insertNode = Node(inputs[1], fNode, fNode.nextNode)
        fNode.nextNode.prevNode = insertNode
        fNode.nextNode = insertNode
    if command == 'delete':
        deleteNode(searchNode(inputs[1]))
    if command == 'deleteFirst':
        deleteNode(fNode.nextNode)
    if command == 'deleteLast':
        deleteNode(fNode.prevNode)
        #deleteNode(searchLast())
nodeList()

Submission status: Time Limit Exceeded

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

class DLL:
    def __init__(self):
        self.head = Node(None)
        self.head.next = self.head
        self.head.prev = self.head
        self.size = 0
    def insert(self,x):
        n = Node(x)
        temp = self.head.next
        self.head.next.prev = n
        self.head.next = n
        n.next = temp
        n.prev = self.head
        self.size += 1
    def delete(self,x):
        if self.size <= 0:
            print 'underflow'
            exit()
        n = self.head.next
        while n != self.head:
            if n.v == x:
                break
            n = n.next
        if n != self.head:
            n.next.prev = n.prev
            n.prev.next = n.next
            self.size -= 1

    def deleteFirst(self):
        if self.size <= 0:
            print 'underflow'
            exit()
        self.head.next.next.prev = self.head
        self.head.next = self.head.next.next
        self.size -= 1
    def deleteLast(self):
        if self.size <= 0:
            print 'underflow'
            exit()
        self.head.prev.prev.next = self.head
        self.head.prev = self.head.prev.prev
        self.size -= 1


n = int(raw_input())
dll = DLL()
for _ in range(n):
    op = raw_input().split(' ')
    if len(op) == 1:
        if op[0][6] == 'F':
            dll.deleteFirst()
        else:
            dll.deleteLast()
    else:
        if op[0][0] == 'i':
            dll.insert(int(op[1]))
        elif op[0][0] == 'd':
            dll.delete(int(op[1]))

n = dll.head.next
values = []
while n != dll.head:
    values.append(n.v)
    n = n.next

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

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        if x in self.array:
            del self.array[self.array.index(x)]

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())
    ans = ""

    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if command in ["insert", "delete"]:
            key = operation[1]
            eval("dll." + command + '(' + key + ')')

        else:
            eval("dll." + command + "()")
    for value in dll.array:
        ans += str(value) + " "

    print(ans.rstrip())

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        try:
            del self.array[self.array.index(x)]
        except:
            pass

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())
    ans = ""

    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if command in ["insert", "delete"]:
            key = operation[1]
            eval("dll." + command + '(' + key + ')')

        else:
            eval("dll." + command + "()")
    for value in dll.array:
        ans += str(value) + " "

    print(ans.rstrip())

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        try:
            del self.array[self.array.index(x)]
        except:
            pass

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())
    ans = ""
    
    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if len(command) == 6:
            key = str(operation[1])
            if command == "insert":
                dll.insert(key)
            else:
                dll.delete(key)

        else:
            if command[6] == 'F':
                dll.deleteFirst()
            else:
                dll.deleteLast()

    for value in dll.array:
        ans += str(value) + " "

    print(ans.rstrip())

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        try:
            self.array.remove(x)
        except:
            pass

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())
    ans = ""
    
    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if len(command) == 6:
            key = str(operation[1])
            if command == "insert":
                dll.insert(key)
            else:
                dll.delete(key)

        else:
            if command[6] == 'F':
                dll.deleteFirst()
            else:
                dll.deleteLast()

    for value in dll.array:
        ans += str(value) + " "

    print(ans.rstrip())

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List


def main():

    n = int(input())
    ans = ""
    dll = []
    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if len(command) == 6:
            key = str(operation[1])
            if command == "insert":
                dll.insert(0, key)
            else:
                try:
                    dll.remove(key)
                except:
                    pass

        else:
            if command[6] == 'F':
                dll.pop(0)
            else:
                dll.pop(-1)

    print(' '.join(dll))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List


def main():

    n = int(input())
    dll = []
    for _ in range(n):
        operation = input()[::]
        if operation[0] == 'i':
            dll.insert(0, operation[7:])
        
        elif operation[6] == ' ':
            try:
                dll.remove(operation[7:])
            except:
                pass

        else:
            if operation[6] == 'F':
                dll.pop(0)
            else:
                dll.pop()

    print(' '.join(dll))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def create_nil():
    nil = Node(0)
    nil.next = nil
    nil.prev = nil
    return nil

def insert(objn, addn):
    addn.next = objn.next
    objn.next.prev = addn
    objn.next = addn
    addn.prev = objn

def find(nil, value):
    node = nil.next
    while node != nil:
        if node.value == value:
            return node
        else:
            node = node.next
    return None

def delete_key(nil, value):
    node = find(nil, value)
    if node != None:
        delete(node)

def delete(node):
    node.prev.next = node.next
    node.next.prev = node.prev
    del node

def delete_first(nil):
    delete(nil.next)

def delete_last(nil):
    delete(nil.prev)

def execute(nil, cmd):
    l = cmd.split()
    if l[0] == 'insert':
        insert(nil, Node(int(l[1])))
    elif l[0] == 'delete':
        delete_key(nil, int(l[1]))
    elif l[0] == 'deleteFirst':
        delete_first(nil)
    elif l[0] == 'deleteLast':
        delete_last(nil)

def print_list(nil):
    out = ''
    node = nil.next
    while node != nil:
        out += '{} '.format(node.value)
        node = node.next
    print(out[:-1])

def main():
    N = int(input())
    nil = create_nil()
    for i in range(N):
        execute(nil, input())
    print_list(nil)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

import sys
from collections import deque

#n, q = map(int, input().split())
n = int(input())
tasks = {
    "insert": "appendleft",
    "delete": "remove",
    "deleteFirst": "popleft",
    "deleteLast": "pop"
}

a = deque()

for i in range(n):
    input_line = input()
    if input_line in tasks:
        #deleteFirst,deleteLast
        task = input_line
        eval("a.{}()".format(tasks[task]))
    else:
        #insert,delete
        try:
            task, item = input_line.split()
            eval("a.{}({})".format(tasks[task], item))
        except:
            pass

print(*a)

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
# Doubly Linked List

class DLL:

    def __init__(self):
        self.array = []

    def insert(self, x):
        self.array = [x] + self.array
    
    def delete(self, x):
        try:
            del self.array[self.array.index(x)]
        except:
            pass

    def deleteFirst(self):
        del self.array[0]

    def deleteLast(self):
        del self.array[len(self.array)-1]


def main():

    dll = DLL()
    n = int(input())

    for _ in range(n):
        operation = input().split()
        command = operation[0]
        if command in ["insert", "delete"]:
            key = operation[1]
            eval("dll." + command + '(' + key + ')')

        else:
            eval("dll." + command + "()")

    ans = ""
    for x in dll.array:
        ans += str(x) + ' '
    print(ans.strip())
        

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input().strip())

l = []
for _ in range(n):
    cmd = input()
    if cmd == "deleteFirst":
        l = l[1:]
    elif cmd == "deleteLast":
        l.pop()
    elif cmd.startswith("insert "):
        _, e = cmd.split(" ")
        l.insert(0, e)
    elif cmd.startswith("delete "):
        _, e = cmd.split(" ")
        if e in l:
            l.remove(e)

print(" ".join(l))

Submission status: Time Limit Exceeded

Solution code:
n = int(input().strip())

l = []
for _ in range(n):
    cmd = input()
    if cmd == "deleteFirst":
        l = l[1:]
    elif cmd == "deleteLast":
        l.pop()
    elif cmd.startswith("insert "):
        _, e = cmd.split(" ")
        l = [e] + l
    elif cmd.startswith("delete "):
        _, e = cmd.split(" ")
        if e in l:
            l.remove(e)

print(" ".join(l))

Submission status: Time Limit Exceeded

Solution code:
n = int(input().strip())

l = []
for _ in range(n):
    cmd = input()
    if cmd == "deleteFirst":
        l = l[1:]
    elif cmd == "deleteLast":
        l.pop()
    elif cmd.startswith("insert "):
        _, e = cmd.split(" ")
        l = [e] + l
    elif cmd.startswith("delete "):
        _, e = cmd.split(" ")
        try:
            l.remove(e)
        except ValueError:
            pass

print(" ".join(l))

Submission status: Time Limit Exceeded

Solution code:
import sys

class E(object):
    def __init__(self, p = None, v = None, n = None):
        self.p = p
        self.v = v
        self.n = n

    def rem(self):
        if self.p is not None:
            self.p.n = self.n
        if self.n is not None:
            self.n.p = self.p

    def ins(self, ne):
        self.p = ne
        ne.n = self

    def prt(self):
        sys.stdout.write(self.v)
        if self.n is not None:
            sys.stdout.write(" ")
            self.n.prt()

fe = le = None

n = int(input().strip())

for _ in range(n):
    cmd = input()
    if cmd == "deleteFirst":
        if fe is not None:
            fe.rem()
            if fe.n is not None:
                fe = fe.n
            else:
                fe = le = None
    elif cmd == "deleteLast":
        if le is not None:
            le.rem()
            if le.p is not None:
                le = le.p
            else:
                fe = le = None
    elif cmd.startswith("insert "):
        _, v = cmd.split(" ")
        e = E(None, v, None)
        if fe is not None:
            fe.ins(e)
        fe = e
        if le is None:
            le = e
    elif cmd.startswith("delete "):
        _, v = cmd.split(" ")
        e = fe
        while e is not None:
            if e.v == v:
                e.rem()
                if fe == e:
                    fe = e.n
                if le == e:
                    le = e.p
                break
            e = e.n

    #print("F: {}, L: {}".format(fe.v if fe is not None else "None", le.v if le is not None else "None"))

if fe is not None:
    fe.prt()
print("")

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

if __name__ == '__main__':
	num = int(input())
	output = ''
	link = []
	for i in range(num):
		order = input()
		if order[:7] == 'insert ':
				link.insert(0, order[7:])
		elif order[:7] == 'delete ':
				if order[7:] in link:
					link.remove(order[7:])
		elif order == 'deleteFirst':
				link.pop(0)
		elif order == 'deleteLast':
				link.pop()
	for j in link:
		output = output + j + ' '
	print(output[:(len(output)-1)])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

if __name__ == '__main__':
	num = int(input())
	output = ''
	link = []
	for i in range(num):
		order = input()
		if 't ' in order:
				link.insert(0, order[7:])
		elif 'e ' in order:
				if order[7:] in link:
					link.remove(order[7:])
		elif 'F' in order:
				link.pop(0)
		elif 'L' in order:
				link.pop()
	for j in link:
		output = output + j + ' '
	print(output[:(len(output)-1)])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

ans = []
for i in range(n):
    c = input().split()
    cmd = c[0]
    x = 0
    if 1 < len(c):
        x = int(c[1])
    if cmd == 'insert':
        y = [x] + ans
        ans = y
    elif cmd == 'delete':
        try:
            index = ans.index(x)
            ans.pop(index)
        except:
            ''
    elif cmd == 'deleteFirst':
        ans.pop(0)
    elif cmd == 'deleteLast':
        ans.pop(len(ans) - 1)

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
li = []
for i in range(n):
    command = input().split()
    if command[0] == 'insert':
        li.insert(0, command[1])
    elif command[0] == 'delete':
        if command[1] in li:
            li.remove(command[1])
    elif command[0] == 'deleteFirst':
        li.pop(0)
    else:
        li.pop()
print(*li)

Submission status: Time Limit Exceeded

Solution code:
class LinkedList(object):
    def __init__(self):
        self.data = []

    def insert(self, d):
        self.data.insert(0, d)

    def delete(self, d):
        if d in self.data:
            self.data.remove(d)

    def delete_first(self):
        self.data.pop(0)

    def delete_last(self):
        self.data.pop(len(self.data)-1)

data = LinkedList()
for _ in range(int(input())):
    line_data = input().split()
    command = line_data[0]
    if len(line_data) == 2:
        d = int(line_data[1])

    if command == 'insert':
        data.insert(d)
    elif command == 'delete':
        data.delete(d)
    elif command == 'deleteFirst':
        data.delete_first()
    elif command == 'deleteLast':
        data.delete_last()

print(" ".join(list(map(str, data.data))))

Submission status: Time Limit Exceeded

Solution code:
cnt=input()
lst=[]
for x in xrange(cnt):
    cmd = raw_input().split()
    if cmd[0] == "insert":
        lst = [int(cmd[1])] + lst
    elif cmd[0] == "delete":
        if int(cmd[1]) in lst:
            lst.remove(int(cmd[1]))
    elif cmd[0] == "deleteFirst":
        if len(lst) > 0:
            lst = lst[1:]
    elif cmd[0] == "deleteLast":
        if len(lst) > 0:
            lst = lst[:-1]
print " ".join([str(x) for x in lst])

Submission status: Time Limit Exceeded

Solution code:
#coding:UTF-8
def DLL(n,C):
    ans=[]
    for i in range(n):
        if C[i]=="deleteFirst":
            ans.pop(len(ans)-1)
        elif C[i]=="deleteLast":
            ans.pop(0)
        else:
            command=C[i].split(" ")[0]
            num=C[i].split(" ")[1]
            if command=="delete":
                for i in reversed(range(len(ans))):
                    if ans[i]==num:
                        ans.pop(i)
                        break
            else:
                ans.append(num)
    ans.reverse()
    print(" ".join(ans))
        
  
if __name__=="__main__":
    n=int(input())
    Command=[]
    for i in range(n):
        Command.append(input())
    DLL(n,Command)

Submission status: Time Limit Exceeded

Solution code:
#coding:UTF-8
def DLL(n,C):
    ans=[]
    for i in range(n):
        if C[i]=="deleteFirst":
            ans.pop(len(ans)-1)
        elif C[i]=="deleteLast":
            ans.pop(0)
        else:
            command=C[i].split(" ")[0]
            num=C[i].split(" ")[1]
            if command=="delete":
                if num in ans:
                    ans.reverse()
                    ans.pop(ans.index(num))
                    ans.reverse()
                else:
                    continue
            else:
                ans.append(num)
    ans.reverse()
    print(" ".join(ans))
        
  
if __name__=="__main__":
    n=int(input())
    Command=[]
    for i in range(n):
        Command.append(input())
    DLL(n,Command)