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 DoublyLinkedList:
    def __init__(self):
        self.nil = self.make_node(None)
        self.nil['next'] = self.nil
        self.nil['prev'] = self.nil

    def make_node(self,v):
        return {'key':v, 'next':None, 'prev':None}

    def dump(self):
        n = self.nil['next']
        while True:
            if n['key'] == None:
                break
            else:
                print str(n['key']),
                n = n['next']
        print


    def insert(self,v):
        n = self.make_node(v)
        n['next'] = self.nil['next']
        self.nil['next']['prev'] = n
        n['prev'] = self.nil
        self.nil['next'] = n

    def delete(self,v):
        self.delete_node(self.list_search(v))

    def delete_node(self,n):
        if n['key'] == None: return
        n['next']['prev'] = n['prev']
        n['prev']['next'] = n['next']

    def list_search(self,v):
        cur = self.nil['next']
        while (cur['key'] != None) and (cur['key'] != v):
            cur = cur['next']
        return cur

    def deleteFirst(self):
        self.delete_node(self.nil['next'])

    def deleteLast(self):
        self.delete_node(self.nil['prev'])

n = int(raw_input())
commands = []
for i in range(n):
    commands.append(raw_input())

l = DoublyLinkedList()
for c in commands:
    a = c[6]
    if a == "F":
        l.deleteFirst()
    elif a == "L":
        l.deleteLast()
    else:
        val = int(c[7:])
        op = c[0]
        if op == "i":
            l.insert(val)
        else:
            l.delete(val)

l.dump()

Submission status: Time Limit Exceeded

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

n = int(input())
ans = []

for i in range(n):
    command = input().split()
    if command[0] == "insert":
        ans.insert(0, command[1])
    elif ans == []:
        continue
    elif command[0] == "delete":
        try:
            ans.remove(command[1])
        except:
            pass
    elif command[0] == "deleteFirst":
        ans.pop(0)
    else:
        ans.pop()

print (' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
command = [input().split() for i in range(n)]
ans = []

for i in range(n):
    if command[i][0] == "insert":
        ans.insert(0, command[i][1])
    elif ans == []:
        continue
    elif command[i][0] == "delete":
        try:
            ans.remove(command[i][1])
        except:
            continue
    elif command[i][0] == "deleteFirst":
        ans.pop(0)
    else:
        ans.pop()

print (' '.join(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def insert(x, dll):
    dll.appendleft(x)

def delete(x, dll):
    try:
        dll.remove(x)
    except ValueError:
        pass

def deleteFirst(dll):
    dll.popleft()

def deleteLast(dll):
    dll.pop()

n = int(input())
command1 = {"insert": insert, "delete": delete}
command2 = {"deleteFirst": deleteFirst, "deleteLast": deleteLast}
dll = deque()
for i in range(n):
    input_line = [str(s) for s in input().split()]
    if(input_line[0] in command1):
        command1[input_line[0]](int(input_line[1]), dll)
    else:
        command2[input_line[0]](dll)
print(*dll)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
dll = deque()

for i in range(n):
    input_line = [str(s) for s in input().split()]
    if input_line[0] == "insert":
        dll.appendleft(int(input_line[1]))
    elif input_line[0] == "delete":
        try:
            dll.remove(int(input_line[1]))
        except ValueError:
            pass
    elif input_line[0] == "deleteFirst":
        dll.popleft()
    else:
        dll.pop()
print(*dll)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
dll = deque()

for i in range(n):
    input_line = [str(s) for s in input().split()]
    if input_line[0][0] == "i":
        dll.appendleft(int(input_line[1]))
    elif input_line[0] == "delete":
        try:
            dll.remove(int(input_line[1]))
        except:
            pass
    elif input_line[0][6] == "F":
        dll.popleft()
    else:
        dll.pop()
        
print(*dll)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
dll = deque()

for i in range(n):
    input_line = [str(s) for s in input().split()]
    if input_line[0] == "insert":
        dll.appendleft(input_line[1])
    elif input_line[0] == "delete":
        try:
            dll.remove(input_line[1])
        except:
            pass
    elif input_line[0] == "deleteFirst":
        dll.popleft()
    else:
        dll.pop()
        
print(*dll)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
n = int(input())
dll = deque()
 
for i in range(n):
    input_line = [str(s) for s in input().split()]
    if input_line[0] == "insert":
        dll.appendleft(input_line[1])
    elif len(dll) == 0:
        continue
    elif input_line[0] == "delete":
        try:
            dll.remove(input_line[1])
        except:
            pass
    elif input_line[0] == "deleteFirst":
        dll.popleft()
    else:
        dll.pop()
         
print(*dll)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

l_l = list()
for i in range(n):
    cmd_l = input().split()
    cmd = cmd_l[0]

    if cmd == "insert":
        l_l.insert(0, cmd_l[1])
    elif cmd == "delete":
        if cmd_l[1] in l_l:
            l_l.remove(cmd_l[1])
    elif cmd == "deleteFirst":
        del l_l[0]
    elif cmd == "deleteLast":
        del l_l[-1]

print(' '.join(l_l))

Submission status: Time Limit Exceeded

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

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

    if len(inputs) == 1:
        if commandName == 'deleteFirst':
            lists.pop(0)
        elif commandName == 'deleteLast':
            lists.pop(-1)
    else:
        num = inputs[1]

        if commandName == 'insert':
            lists = [num] + lists
        elif commandName == 'delete':
            if num in lists:
                lists.remove(num)

print(' '.join(lists))

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedList:
    def __init__(self):
        self.first = Node(-1)
        self.first.setNext(Node(-1))

    def insert(self, value):
        newNode = Node(value)
        newNode.setNext(self.first.getNext())
        newNode.setPrev(self.first)
        self.first.getNext().setPrev(newNode)
        self.first.setNext(newNode)

    def delete(self, value):
        self.first.delete(value)

    def deleteFirst(self):
        if self.first.getNext().getValue() != -1:
            self.first.setNext(self.first.getNext().getNext())
            self.first.getNext().setPrev(self.first)

    def deleteLast(self):
        self.first.deleteLast()

    def printAll(self):
        if self.first.getNext().getValue() != -1:
            self.first.getNext().printAll()

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

    def getValue(self):
        return self.value

    def setValue(self, value):
        self.value = value

    def getNext(self):
        return self.next

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

    def getPrev(self):
        return self.prev

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

    def delete(self, value):
        nextValue = self.next.getValue()
        if nextValue == value:
            self.next = self.next.getNext()
            self.next.setPrev(self)
        elif nextValue != -1:
            self.next.delete(value)

    def deleteLast(self):
        if self.next.getValue() == -1:
            self.prev.setNext(self.next)
            self.next.setPrev(self.prev)
        else:
            self.next.deleteLast()

    def printAll(self):
        if self.next.getValue() != -1:
            print self.value,
            self.next.printAll()
        else:
            print self.value

if __name__ == "__main__":
    dll = DoublyLinkedList()

    N = input()
    for i in range(N):
        raw = raw_input().split()
        com = raw[0]
        if len(raw) > 1:
            value = int(raw[1])
        if com == "insert":
            dll.insert(value)
        elif com == "delete":
            dll.delete(value)
        elif com == "deleteFirst":
            dll.deleteFirst()
        else:
            dll.deleteLast()
    dll.printAll()

Submission status: Time Limit Exceeded

Solution code:
A = []
n = input()

for i in range(n):
    command = raw_input().split()

    if command[0] == 'insert':
        A.insert(0, command[1])
    elif command[0] == 'delete':
        if A.count(command[1]) != 0:
            A.remove(command[1])
    elif command[0] == 'deleteFirst':
        A.pop(0)
    elif command[0] == 'deleteLast':
        A.pop()

for i in range(len(A)):
    print A[i],

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedList:
    def __init__(self, value = -1):
        self.value = value
        self.prev = self
        self.next = self

    def insert(self, value):
        newNode = DoublyLinkedList(value)
        newNode.next = self.next
        newNode.prev = self
        self.next.prev = newNode
        self.next = newNode

    def delete(self, value):
        node = self.next
        while node.value != -1:
            if node.value == value:
                node.next.prev = node.prev
                node.prev.next = node.next
                break
            node = node.next

    def deleteFirst(self):
        if self.next.value != -1:
            self.next = self.next.next
            self.next.prev = self

    def deleteLast(self):
        if self.prev.value != -1:
            self.prev = self.prev.prev
            self.prev.next = self

    def printAll(self):
        node = self.next
        while node.next.value != -1:
            print node.value,
            node = node.next
        print node.value

if __name__ == "__main__":
    dll = DoublyLinkedList()

    N = input()
    for i in range(N):
        raw = raw_input().split()
        com = raw[0]
        if len(raw) > 1:
            value = int(raw[1])
        if com == "insert":
            dll.insert(value)
        elif com == "delete":
            dll.delete(value)
        elif com == "deleteFirst":
            dll.deleteFirst()
        else:
            dll.deleteLast()
    dll.printAll()

Submission status: Time Limit Exceeded

Solution code:
import sys

class DoublyLinkedList:
    def __init__(self, value = -1):
        self.value = value
        self.prev = self
        self.next = self

    def insert(self, value):
        newNode = DoublyLinkedList(value)
        newNode.next = self.next
        newNode.prev = self
        self.next.prev = newNode
        self.next = newNode

    def delete(self, value):
        node = self.next
        while node.value != -1:
            if node.value == value:
                node.next.prev = node.prev
                node.prev.next = node.next
                break
            node = node.next

    def deleteFirst(self):
        if self.next.value != -1:
            self.next = self.next.next
            self.next.prev = self

    def deleteLast(self):
        if self.prev.value != -1:
            self.prev = self.prev.prev
            self.prev.next = self

    def printAll(self):
        node = self.next
        while node.next.value != -1:
            print node.value,
            node = node.next
        print node.value

if __name__ == "__main__":
    dll = DoublyLinkedList()
    N = input()
    lines = sys.stdin.readlines()
    for line in lines:
        raw = line.split()
        com = raw[0]
        if len(raw) > 1:
            value = int(raw[1])
        if com == "insert":
            dll.insert(value)
        elif com == "delete":
            dll.delete(value)
        elif com == "deleteFirst":
            dll.deleteFirst()
        else:
            dll.deleteLast()
    dll.printAll()

Submission status: Time Limit Exceeded

Solution code:
import sys

class DoublyLinkedList:
    def __init__(self, value = -1):
        self.value = value
        self.prev = self
        self.next = self

    def insert(self, value):
        newNode = DoublyLinkedList(value)
        newNode.next = self.next
        newNode.prev = self
        self.next.prev = newNode
        self.next = newNode

    def delete(self, value):
        node = self.next
        while node.value != -1:
            if node.value == value:
                node.next.prev = node.prev
                node.prev.next = node.next
                break
            node = node.next

    def deleteFirst(self):
        if self.next.value != -1:
            self.next = self.next.next
            self.next.prev = self

    def deleteLast(self):
        if self.prev.value != -1:
            self.prev = self.prev.prev
            self.prev.next = self

    def printAll(self):
        node = self.next
        while node.next.value != -1:
            print node.value,
            node = node.next
        print node.value

if __name__ == "__main__":
    dll = DoublyLinkedList()
    N = input()
    lines = sys.stdin.readlines()
    for line in lines:
        line = line.split()
        cmd = line[0]
        if cmd == "insert":
            dll.insert(int(line[1]))
        elif cmd == "delete":
            dll.delete(int(line[1]))
        elif cmd == "deleteFirst":
            dll.deleteFirst()
        else:
            dll.deleteLast()
    dll.printAll()

Submission status: Time Limit Exceeded

Solution code:
def insert(x,a):
    a.insert(0,x)
    return a
def delete(x,a):
    if x in a:
        a.remove(x)
    else:
        return
    return a
def deletefirst(a):
    del a[0]
    return a
def deletelast(a):
    del a[-1]
    return a
n=input()
a=[]
for i in xrange(n):
    s=raw_input().split()
    if s[0]=="insert":
        insert(s[1],a)
    elif s[0]=="delete":
        delete(s[1],a)
    elif s[0]=="deleteFirst":
        deletefirst(a)
    else:
        deletelast(a)
print(" ".join(a))

Submission status: Time Limit Exceeded

Solution code:
def insert(x,a):
    a.insert(0,x)
def delete(x,a):
    if x in a:
        a.remove(x)
    else:
        return
def deletefirst(a):
    del a[0]
def deletelast(a):
    del a[-1]
n=input()
a=[]
for i in xrange(n):
    s=raw_input().split()
    if s[0]=="insert":
        insert(s[1],a)
    elif s[0]=="delete":
        delete(s[1],a)
    elif s[0]=="deleteFirst":
        deletefirst(a)
    else:
        deletelast(a)
print(" ".join(a))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
stack = []
for i in range(n):
    command = list(input().split())
#    print(stack, command)
    if command[0] == 'insert':
        stack = [command[1]] + stack
    elif command[0] == 'delete':
        if command[1] in stack:
            stack.remove(command[1])
    elif command[0] == 'deleteFirst':
        stack.pop(0)
    elif command[0] == 'deleteLast':
        stack.pop()
print(' '.join(stack))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
stack = []
j = 0
for i in range(n):
    command = list(input().split())
#    print(stack, command)
    if command[0] == 'insert':
        stack.append(command[1])
    elif command[0] == 'delete':
        if command[1] in stack:
            temp = list(reversed(stack[j:]))
            temp.remove(command[1])
            stack = list(reversed(temp))
            j = 0
    elif command[0] == 'deleteFirst':
        stack.pop()
    elif command[0] == 'deleteLast':
        j += 1
j=None if j==0  else j-1
print(' '.join(stack[-1:j:-1]))

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedList(object):

    def __init__(self):
        self.dict = {}
        self.gen_node = node_generator()

        nil = 0
        self.nil_node = self.gen_node(0, nil, nil)
        self.dict[nil] = self.nil_node

    def insert(self, x):
        inserted = self.gen_node(x, self.nil_node.p, self.nil_node.next)
        self.dict[inserted.p] = inserted

        self.dict[self.nil_node.next].prev = inserted.p
        self.nil_node.next = inserted.p

    def _delete_node(self, i):
        self.dict[self.dict[i].prev].next, self.dict[self.dict[i].next].prev = self.dict[i].next, self.dict[i].prev
        del(self.dict[i])

    def _search_node(self, val):
        cur = self.nil_node.next
        while cur != self.nil_node.p:
            if self.dict[cur].val == val:
                return cur
            cur = self.dict[self.dict[cur].next].p

    def delete(self, x):
        i = self._search_node(x)
        if i is not None:
            self._delete_node(i)

    def delete_first(self):
        self._delete_node(self.nil_node.next)

    def delete_last(self):
        self._delete_node(self.nil_node.prev)

    def show(self):
        ans = ""
        cur = self.nil_node.next

        while cur != self.nil_node.p:
            ans += "{} ".format(self.dict[cur].val)
            cur = self.dict[cur].next

        print ans.strip()


class Node(object):

    def __init__(self, p, val, prev, _next):
        self.p = p
        self.val = val
        self.prev = prev
        self.next = _next

    def __repr__(self):
        return "p: {}, val: {}, prev: {}, next: {}\n".format(self.p, self.val, self.prev, self.next)


def node_generator():
    p = [-1]

    def _node_generator(val, prev, _next):
        p[0] += 1
        return Node(p[0], val, prev, _next)

    return _node_generator

if __name__ == '__main__':
    n = int(raw_input())
    commands = [raw_input().split() for _ in range(n)]

    d = DoublyLinkedList()

    for command in commands:
        if command[0] == "insert":
            d.insert(int(command[1]))
        elif command[0] == "delete":
            d.delete(int(command[1]))
        elif command[0] == "deleteFirst":
            d.delete_first()
        elif command[0] == "deleteLast":
            d.delete_last()

    d.show()

Submission status: Time Limit Exceeded

Solution code:
class DoublyLinkedList(object):

    def __init__(self):
        nil_node = Node(-1, -1, -1)
        self.nil_node = nil_node
        self.nil_node.prev = nil_node
        self.nil_node.next = nil_node

    def insert(self, x):
        inserted = Node(x, self.nil_node, self.nil_node.next)
        self.nil_node.next.prev = inserted
        self.nil_node.next = inserted

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

    def _search_node(self, val):
        cur = self.nil_node.next
        while cur.val != self.nil_node.val:
            if cur.val == val:
                return cur
            cur = cur.next

    def delete(self, val):
        node = self._search_node(val)
        if node is not None:
            self._delete_node(node)

    def delete_first(self):
        self._delete_node(self.nil_node.next)

    def delete_last(self):
        self._delete_node(self.nil_node.prev)

    def show(self):
        ans = ""
        cur = self.nil_node.next

        while cur.val != self.nil_node.val:
            ans += "{} ".format(cur.val)
            cur = cur.next

        print ans.strip()


class Node(object):

    def __init__(self, val, prev, _next):
        self.val = val
        self.prev = prev
        self.next = _next

    def __repr__(self):
        return "val: {}, prev: {}, next: {}\n".format(self.val, self.prev.val, self.next.val)

if __name__ == '__main__':
    n = int(raw_input())
    commands = [raw_input().split() for _ in range(n)]

    d = DoublyLinkedList()

    for command in commands:
        if command[0] == "insert":
            d.insert(int(command[1]))
        elif command[0] == "delete":
            d.delete(int(command[1]))
        elif command[0] == "deleteFirst":
            d.delete_first()
        elif command[0] == "deleteLast":
            d.delete_last()

    d.show()

Submission status: Time Limit Exceeded

Solution code:
def insert(o,dll):
    dll.insert(0,o)
def delete(o,dll):
    if not o in dll:
        return
    dll.remove(o)
def deleteFirst(dll):
    dll.pop(0)
def deleteLast(dll):
    dll.pop(-1)

def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                deleteFirst(dll)
            elif tmp[0] == "deleteLast":
                deleteLast(dll)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            operand = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                insert(operand,dll)
            elif command == "delete":
                delete(operand,dll)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                dll.pop(0)
            elif tmp[0] == "deleteLast":
                dll.pop(-1)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            o = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                dll.insert(0,o)
            elif command == "delete":
                if o in dll:
                    dll.remove(o)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                dll.pop(0)
            elif tmp[0] == "deleteLast":
                dll.pop(-1)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            o = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                dll = [o]+dll
            elif command == "delete":
                if o in dll:
                    dll.remove(o)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                dll.pop(0)
            elif tmp[0] == "deleteLast":
                dll.pop(-1)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            o = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                dll = [o]+dll
            elif command == "delete":
                if o in set(dll):
                    dll.remove(o)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import time
def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                dll.pop(0)
            elif tmp[0] == "deleteLast":
                dll.pop(-1)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            o = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                dll.insert(0,o)
            elif command == "delete":
                if o in set(dll):
                    dll.remove(o)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    # f = time.clock()
    main()
    # t = time.clock()
    # print t-f

Submission status: Time Limit Exceeded

Solution code:
#! -*-coding:utf-8-*-
# linked list????§???????????????????
class Deque:
    class Cell:
        def __init__(self,x,y=None,z=None):
            self.data = x
            self.next = y
            self.prev = z
    def __init__(self):
        head = Deque.Cell(None)
        head.next = head
        head.prev = head
        self.size = 0
        self.head = head
    def my_insert(self,x):
        h = self.head
        q = h.next
        p = Deque.Cell(x,q,h)
        h.next = p
        q.prev = p
        self.size +=1
    def my_del(self,x):
        if self.size==0:
            return
        h=self.head
        # h = self.head.next
        # num=self.size
        # while num > 0:
        #     if h.data == x:
        #         p = h.prev
        #         n = h.next
        #         h.prev.next = n
        #         h.next.prev = p
        #         self.size -=1
        #     h=h.next
        #     num -= 1

        cp_h=h
        while True:
            h = h.next
            if h==cp_h:
                break
            if h.data == x:
                p = h.prev
                n = h.next
                h.prev.next = n
                h.next.prev = p
                self.size -=1
                break
    def my_deleteFirst(self):
        if self.size==0:
            return
        h = self.head.next
        p = h.prev
        n = h.next
        h.prev.next = n
        h.next.prev = p
        self.size-=1
    def my_deleteLast(self):
        if self.size==0:
            return
        h=self.head.prev
        p = h.prev
        n = h.next
        h.prev.next=n
        h.next.prev = p
        self.size-=1
    # ??¨???
    def __str__(self):
        if self.size == 0: return ''
        buff = ''
        n = self.size
        cp = self.head.next
        while n > 1:
            buff += '%s ' % cp.data
            cp = cp.next
            n -= 1
        buff += '%s' % cp.data
        return buff

def main():
    q = Deque()
    num = input()
    i=0
    while True:
        if i>=num:
            break
        tmp = raw_input().split()
        if len(tmp)==1:
            if tmp[0]=="deleteFirst":
                q.my_deleteFirst()
            elif tmp[0]=="deleteLast":
                q.my_deleteLast()
            else:
                print "This command is invalid."
                return
        elif len(tmp)==2:
            if tmp[0]=="insert":
                q.my_insert(int(tmp[1]))
            elif tmp[0]=="delete":
                q.my_del(int(tmp[1]))
            else:
                print "This command is invalid."
                return
        else:
            print "This command is invalid."
            return
        # print q
        i+=1
    print q

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

import time
def main():
    n = input()
    dll = []
    for _ in xrange(n):
        tmp = raw_input().split()
        if len(tmp) == 1:
            # print dll
            # print tmp[0]
            if tmp[0] == "deleteFirst":
                # print "deleteFirst..."
                dll.pop(0)
            elif tmp[0] == "deleteLast":
                # print "deleteLast..."
                dll.pop(-1)
            else:
                print "This command is invalid."
                break
        elif len(tmp)==2:
            command = tmp[0]
            o = tmp[1]
            # print dll
            # print command, operand
            if command == "insert":
                # print "insert..."
                dll.insert(0,o)
            elif command == "delete":
                # print "delete..."
                if o in set(dll):
                    dll.remove(o)
            else:
                print "This command is invalid."
                break
    print " ".join(map(str,dll))

if __name__ == '__main__':
    # f = time.clock()
    main()
    # t = time.clock()
    # print t-f

Submission status: Time Limit Exceeded

Solution code:
n = input()
lis = []
for i in xrange(n):
    com = raw_input()
    try:
        com, x = com.split()
        if   com == 'insert':
            lis.append(x)
        elif com == 'delete':
            l = len(lis) - 1
            while (lis[l] != x) and l >= 0:
                l -= 1
            if lis[l] == x:
                lis.pop(l)
    except:
        if com == 'deleteFirst':
            lis.pop()
        if com == 'deleteLast':
            lis.pop(0)

print " ".join( map(str, reversed(lis)) )