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: Runtime Error

Solution code:
#coding:utf-8
from collections import deque
from numba import jit
n = int(input())

@jit
def ord(order): 
    if order[0] == "insert":
        day.appendleft(order[1])
    elif order[0] == "delete":
        try:
            day.remove(order[1])
        except:
            pass
    elif order[0] == "deleteFirst":
        day.popleft()
    elif order[0] == "deleteLast":
        day.pop()


day = deque()
for i in range(n):
    order = list(input().split())
    ord(order)
day = " ".join(day)              
print(day)

Submission status: Runtime Error

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

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

    def delete(self, x):
        self.data.remove(x)

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

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


def print_list_split_whitespace(a):
    for x in a[:-1]:
        print(x, end=' ')
    print(a[-1])


dll = DoublyLinkedList()

n = int(input())
for _ in range(n):
    command = input().split()
    if command[0] == "insert":
        dll.insert(int(command[1]))
    elif command[0] == "delete":
        dll.delete(int(command[1]))
    elif command[0] == "deleteFirst":
        dll.deleteFirst()
    elif command[0] == "deleteLast":
        dll.deleteLast()
    else:
        raise ValueError("No Command such as", command[0])

print_list_split_whitespace(dll.data)

Submission status: Runtime Error

Solution code:
if __name__ == '__main__':
    store = list()
    for i in range(int(input())):
        parts = input().split()
        cmd = parts[0]
        if cmd == 'insert':
            store.insert(0, int(parts[1]))
        elif cmd == 'delete':
            num = int(parts[1])
            store.remove(num)
        elif cmd == 'deleteFirst':
            store.remove(store[0])
        elif cmd =='deleteLast':
            store = store[:-1]
    print(' '.join(map(str, store)))

Submission status: Runtime Error

Solution code:


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

    def __init__(self, dtype):
        self.dtype = dtype
        self.dummy = LinkedList.Node(dtype())
        self.dummy.next = self.dummy
        self.dummy.prev = self.dummy

        self.dict = dict()

    def insert(self, x):
        node = LinkedList.Node(x, self.dummy.next, self.dummy)

        self.dummy.next.prev = node
        self.dummy.next = node

        self.dict[x] = node
    
    def delete(self, x):
        if x in self.dict:
            node = self.dict[x]
            self.__remove_node(node)
    
    def deleteLast(self):
        node = self.dummy.prev
        if node != self.dummy:
            self.__remove_node(node)
    
    def deleteFirst(self):
        node = self.dummy.next
        if node != self.dummy:
            self.__remove_node(node)

    def __remove_node(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
        self.dict.pop(node.value)

    def items(self):
        node = self.dummy.next
        while node != self.dummy:
            yield node.value
            node = node.next


store = LinkedList(str)
for i in range(int(input())):
    parts = input().split()
    cmd = parts[0]
    if cmd == 'insert':
        store.insert(parts[1])
    elif cmd == 'delete':
        store.delete(parts[1])
    elif cmd == 'deleteFirst':
        store.deleteFirst()
    elif cmd =='deleteLast':
        store.deleteLast()

print(' '.join(store.items()))

Submission status: Runtime Error

Solution code:
import java.util.Iterator;
import java.util.Scanner;
import java.util.LinkedList;

public class Main {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		LinkedList<Integer> list = new LinkedList<Integer>();
		for (int i = 0; i < n; i++) {
			String command = sc.next();
			if (command.equals("insert") || command.equals("delete")) {
				Integer value = sc.nextInt();
				if (command.equals("insert")) {
					list.addFirst(value);
				} else {
					list.remove(value);
				}
			} else if (command.equals("deleteFirst")) {
				list.removeFirst();
			} else if (command.equals("deleteLast")) {
				list.removeLast();
			} else {
				System.out.println("Unknown command:" + command);
			}
		}
		sc.close();	
		Iterator<Integer> itr = list.iterator();
		while (itr.hasNext()) {
			Integer value = itr.next();
			System.out.print(value);
			if (itr.hasNext()) {
				System.out.print(" ");
			}
		}
		System.out.println("");
	}	
}

Submission status: Runtime Error

Solution code:
from collections import deque

def main():
    N = int(input())
    L = deque([])

    for _ in range(N):
        command_value = input()

        if len(command_value.split()) == 2:
            command, value = command_value.split()
        else:
            command = command_value
            value = None

        if command == "insert":
            L.append(value)
        elif command == "delete":
            L.remove(value)
        elif command == "deleteFirst":
            L.popleft()
        elif command == "deleteLast":
            L.pop()

    L = list(L)
    print(" ".join(L[::-1]))

main()

Submission status: Runtime Error

Solution code:
from collections import deque

def main():
    N = int(input())
    L = deque([])

    for _ in range(N):
        command_value = input()

        if len(command_value.split()) == 2:
            command, value = command_value.split()
        else:
            command = command_value
            value = None

        if command == "insert":
            L.insert(0, value)
        elif command == "delete":
            L.remove(value)
        elif command == "deleteFirst":
            L.popleft()
        elif command == "deleteLast":
            L.pop()

    print(" ".join(L))

main()

Submission status: Runtime Error

Solution code:
N = int(input())
lis = []
for n in range(N):
    com = input().split()
    if com[0] == "insert":
        lis.insert(0,int(com[1]))
    elif com[0] == "delete":
        lis.remove(int(com[1]))
    elif com[0] == "deleteFirst":
        del lis[0]
    else:
        lis.pop()
print(*lis)

Submission status: Runtime Error

Solution code:
class Node():
    key = 0
    def __init__( self,  key ):
        self.key = key
        self.next = -1
        self.pre = -1

    def insert( self, othernode ): # othernodeにはinsert前の先頭のノードを入れる
        self.next = othernode
        othernode.pre = self
        return self

    def delete( self, x ): #先頭ノードで実行
        if self.key == x:
            self.pre.next = self.next
            self.next.pre = self.pre
        else :
            self.next.delete( x )

    def printNodes( self ): #先頭ノードで実行
        if self.next.next != -1:
            print( str( self.key ), end=" " )
            self.next.printNodes()
        elif self.next != -1:
            print( str( self.key ), end="\n" )

    def deleteFirst( self ):
        self.next.pre = -1
        return self.next #新しい先頭ノードを返す

    def deleteLast( self ):
        if self.next != -1:
            self.next.deleteLast()
        else :
            self.pre.next = -1


def main():
    n = int( input() )
    commands = []
    vals = []
    for i in range(n):
        tmp = input().split()
        tmp.append( 0 )
        commands.append( tmp[0] )
        vals.append( int(tmp[1]) )

    FirstNode = Node( None )
    for i in range(n):
        if commands[i] == "insert":
            TmpNode = Node( vals[i] )
            FirstNode = TmpNode.insert( FirstNode )
        elif commands[i] == "delete":
            FirstNode.delete( vals[i] )
        elif commands[i] == "deleteFirst":
            FirstNode = FirstNode.deleteFirst()
        elif commands[i] == "deleteLast":
            FirstNode.deleteLast()
        else :
            print("command error!")

    FirstNode.printNodes()

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
class Node():
    key = 0
    def __init__( self,  key ):
        self.key = key
        self.next = -1
        self.pre = -1

    def insert( self, othernode ): # othernodeにはinsert前の先頭のノードを入れる
        self.next = othernode
        othernode.pre = self
        return self

    def delete( self, x ): #先頭ノードで実行
        if self.key == x and self.pre != -1:
            self.pre.next = self.next
            self.next.pre = self.pre
        else :
            self.next.delete( x )

    def printNodes( self ): #先頭ノードで実行
        if self.next.next != -1:
            print( str( self.key ), end=" " )
            self.next.printNodes()
        elif self.next != -1:
            print( str( self.key ), end="\n" )

    def deleteFirst( self ):
        self.next.pre = -1
        return self.next #新しい先頭ノードを返す

    def deleteLast( self ):
        if self.next != -1:
            self.next.deleteLast()
        else :
            self.pre.next = -1


def main():
    n = int( input() )
    commands = []
    vals = []
    for i in range(n):
        tmp = input().split()
        tmp.append( 0 )
        commands.append( tmp[0] )
        vals.append( int(tmp[1]) )

    FirstNode = Node( None )
    for i in range(n):
        if commands[i] == "insert":
            TmpNode = Node( vals[i] )
            FirstNode = TmpNode.insert( FirstNode )
        elif commands[i] == "delete":
            FirstNode.delete( vals[i] )
        elif commands[i] == "deleteFirst":
            FirstNode = FirstNode.deleteFirst()
        elif commands[i] == "deleteLast":
            FirstNode.deleteLast()
        else :
            print("command error!")

    FirstNode.printNodes()

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
class Node():
    key = 0
    def __init__( self,  key ):
        self.key = key
        self.next = -1
        self.pre = -1

    def insert( self, othernode ): # othernodeにはinsert前の先頭のノードを入れる
        self.next = othernode
        othernode.pre = self
        return self

    def delete( self, x ): #先頭ノードで実行
        FirstNode = self
        if self.key == x:
            if self.pre == -1:
                self.next.pre = -1
                FirstNode = self.next
            else :
                self.pre.next = self.next
                self.next.pre = self.pre
        else:
            self.next.delete( x )
        return FirstNode

    def printNodes( self ): #先頭ノードで実行
        if self.next.next != -1:
            print( str( self.key ), end=" " )
            self.next.printNodes()
        elif self.next != -1:
            print( str( self.key ), end="\n" )

    def deleteFirst( self ):
        self.next.pre = -1
        return self.next #新しい先頭ノードを返す

    def deleteLast( self ):
        if self.next != -1:
            self.next.deleteLast()
        else :
            self.pre.next = -1


def main():
    n = int( input() )
    commands = []
    vals = []
    for i in range(n):
        tmp = input().split()
        tmp.append( 0 )
        commands.append( tmp[0] )
        vals.append( int(tmp[1]) )

    FirstNode = Node( None )
    for i in range(n):
        if commands[i] == "insert":
            TmpNode = Node( vals[i] )
            FirstNode = TmpNode.insert( FirstNode )
        elif commands[i] == "delete":
            FirstNode = FirstNode.delete( vals[i] )
        elif commands[i] == "deleteFirst":
            FirstNode = FirstNode.deleteFirst()
        elif commands[i] == "deleteLast":
            FirstNode.deleteLast()
        else :
            print("command error!")

    FirstNode.printNodes()

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    n = int( input() )
    FirstNode = {"pre":-1, "key":None, "next":-1}
    for i in range(n):
        tmp = input().split()
        if tmp[0] == "insert":
            TmpNode = {"pre":FirstNode, "key":tmp[1], "next":-1}
            FirstNode[next] = TmpNode
            FirstNode = TmpNode
        elif tmp[0] == "delete":
            TmpNode = FirstNode
            while True:
                if TmpNode[key] == tmp[1]:
                    if TmpNode[pre] == -1:
                        TmpNode[next][pre] = -1
                        FirstNode = TmpNode[next]
                        break
                    else :
                        TmpNode[pre][next] = TmpNode[next]
                        TmpNode[next][pre] = TmpNode[pre]
                        break
                else :
                    if TmpNode[next] != -1:
                        TmpNode = TmpNode[next]
                        continue
        elif tmp[0] == "deleteFirst":
            FirstNode[next][pre] = -1
            FirstNode = FirstNode[next]
        elif tmp[0] == "deleteLast":
            TmpNode = FirstNode
            while True:
                if TmpNode[next] != -1:
                    TmpNode = TmpNode[next]
                    continue
                else :
                    TmpNode[pre][next] = -1
                    break
        else :
            print("command error!")
    TmpNode = FirstNode
    while True:
        if FirstNode[next][next] != -1:
            print( str( TmpNode[key] ), end=" " )
            TmpNode = TmpNode[next]
        elif TmpNode[next] != -1:
            print( str( TmpNode[key] ), end="\n" )

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
xlist = []
for i in range(n):
    command = list(map(str,input().split()))
    if (command[0] == 'insert'):
        x = command[1]
        if (len(xlist) == 0):
            xlist.append(int(x))
        else:
            xlist.append(int(x))
            for i in range(1,len(xlist)):
                k = len(xlist) - i 
                j = k-1
                xlist[j], xlist[k] = xlist[k], xlist[j]
    elif (command[0] == 'delete'):
        x = command[1]
        if int(x) in xlist :
            xlist.remove(int(x))
    elif (command[0] == 'deleteFirst'):
        if (len(xlist) > 0):
            del xlist[0]
    elif (command[0] == 'deleteLast'):
        if (len(xlist) > 0):
            del xlist[-1]
nx = len(xlist)
for i in range(n):
    if ( i == n-1):
        print('{}'.format(xlist[i]), end = '')
    else:
        print('{}'.format(xlist[i]), end = ' ')

Submission status: Runtime Error

Solution code:
from collections import deque   ##deque 라는 데이터형 편리한듯. print도그렇고 append,pop속도도 빠르고
n = int(input())
xdeque = deque()
for i in range(n):
    command = list(map(str,input().split()))
    if (command[0] == 'insert'):
        x = command[1]
        xdeque.appendleft(int(x))
    elif (command[0] == 'delete'):
        x = command[1]
        try:
            d.remove(int(x))
        except ValueError:
            pass
    elif (command[0] == 'deleteFirst'):
        xdeque.popleft()
    else:
        xdeque.pop()
print(*xdeque)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
from collections import deque   
n = int(input())
d = deque()
for _ in range(n):
    x = input().split()
    if (command[0][0] == 'i'):
        d.appendleft(int(x[1]))
    elif (command[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: Runtime Error

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

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

for i in range(n):
    command, num = list(input().split())

    if command == 'insert':
        key.append(num)
    elif command == 'delete':
        key.remove(num)
    elif command == 'deleteFirst':
        del key[0]
    elif command == 'deleteLast':
        del key[-1]

for i in range(len(key)):
    if i == len(key) - 1:
        print('{0}'.format(key[i]))
    else:
        print('{0}'.format(key[i]), end=' ')

Submission status: Runtime Error

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

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

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

    if command[0] == 'insert':
        key.append(command[1])
    elif command[0] == 'delete':
        key.remove(command[1])
    elif command[0] == 'deleteFirst':
        del key[0]
    elif command[0] == 'deleteLast':
        del key[-1]

for i in range(len(key)):
    if i == len(key) - 1:
        print('{0}'.format(key[i]))
    else:
        print('{0}'.format(key[i]), end=' ')

Submission status: Runtime Error

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

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

for i in range(n + 1):
    command = list(input().split())

    if command[0] == 'insert':
        key.append(command[1])
    elif command[0] == 'delete' and command[1] in key:
        key.remove(command[1])
    elif command[0] == 'deleteFirst':
        del key[0]
    elif command[0] == 'deleteLast':
        del key[-1]

for i in range(len(key)):
    if i == len(key) - 1:
        print('{0}'.format(key[i]))
    else:
        print('{0}'.format(key[i]), end=' ')

Submission status: Runtime Error

Solution code:
l = []
n = int(input())
for _ in range (n):
    cmd = input().split(' ')
    if cmd[0]=='insert':
        l.insert(0,int(cmd[1]))
    if cmd[0]=='delete':
        l.remove(int(cmd[1]))
    if cmd[0]=='deleteFirst':
        l.pop(0)
    if cmd[0]=='deleteLast':
        l.pop(len(l)-1)
print(*l)

Submission status: Runtime Error

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

    def insert(self, node):
        self.nodes.insert(0, node)

    def delete(self, node):
        self.nodes.remove(node)

    def deleteFirst(self):
        self.nodes.pop(0)

    def deleteLast(self):
        self.nodes.pop()

def run():
    n = int(input())
    linked_list = LinkedList()
    for _ in range(n):
        order = [x.strip() for x in input().split()]
        if order[0] == 'insert':
            linked_list.insert(int(order[1]))
        elif order[0] == 'delete':
            linked_list.delete(int(order[1]))
        elif order[0] == 'deleteFirst':
            linked_list.deleteFirst()
        elif order[0] == 'deleteLast':
            linked_list.deleteLast()
    print(' '.join([str(n) for n in linked_list.nodes]))
    
if __name__ == '__main__':
    run()

Submission status: Runtime Error

Solution code:
def run():
    n = int(input())
    nodes = []
    for _ in range(n):
        order = [o.strip() for o in input().split()]
        if order[0] == 'insert':
            nodes.insert(0, (int(order[1]))
        elif order[0] == 'delete':
            if int(order[1]) in nodes:
                nodes.remove(int(order[1]))
        elif order[0] == 'deleteFirst':
            nodes.pop(0)
        elif order[0] == 'deleteLast':
            nodes.pop()
    print(' '.join([str(n) for n in nodes]))
    
if __name__ == '__main__':
    run()

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
l = deque()
count = set([])
for _ in range (n):
    cmd = input().split(' ')
    print(cmd)
    if cmd[0]=='insert':
        l.appendleft(int(cmd[1]))
        if not int(cmd[1]) in count:
            count.add(int(cmd[1]))
    if cmd[0]=='delete':
        if len(l) !=0 and int(cmd[2]) in count:
            l.remove(int(cmd[1]))
    if cmd[0]=='deleteFirst':
        l.popleft()
    if cmd[0]=='deleteLast':
        l.pop()
    print(*l)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
l = deque()
count = set([])
for _ in range (n):
    cmd = input().split(' ')
    if cmd[0]=='insert':
        l.appendleft(int(cmd[1]))
        if not int(cmd[1]) in count:
            count.add(int(cmd[1]))
    if cmd[0]=='delete':
        if len(l) !=0 and int(cmd[2]) in count:
            l.remove(int(cmd[1]))
    if cmd[0]=='deleteFirst':
        l.popleft()
    if cmd[0]=='deleteLast':
        l.pop()
print(*l)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
l = deque()
count = set([])
for _ in range (n):
    cmd = input().split(' ')
    if cmd[0]=='insert':
        l.appendleft(int(cmd[1]))
        if not int(cmd[1]) in count:
            count.add(int(cmd[1]))
    if cmd[0]=='delete':
        if len(l) !=0 and int(cmd[1]) in count:
            l.remove(int(cmd[1]))
    if cmd[0]=='deleteFirst':
        l.popleft()
    if cmd[0]=='deleteLast':
        l.pop()
print(*l)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
l = deque()
count = set([])
for _ in range (n):
    cmd = input().split(' ')
    if cmd[0]=='insert':
        l.appendleft(int(cmd[1]))
        if not int(cmd[1]) in count:
            count.add(int(cmd[1]))
    if cmd[0]=='delete':
        if len(l) !=0 and int(cmd[1]) in count:
            l.remove(int(cmd[1]))
            count.remove(int(cmd[1]))
    if cmd[0]=='deleteFirst':
        count.remove(l.popleft())
    if cmd[0]=='deleteLast':
        count.remove(l.pop())
print(*l)

Submission status: Runtime Error

Solution code:
n = int(raw_input())

li = []
for i in range(n):
    cmd = raw_input().split()
    if cmd[0] == 'insert':
        li.insert(0,cmd[1])
    elif cmd[0] == 'delete':
        li.remove(cmd[1])
    elif cmd[0] == 'deleteFirst':
        li.pop(0)
    elif cmd[0] == 'deleteLast':
        li.pop()
for e in li:
    print e,

Submission status: Runtime Error

Solution code:
n = int(raw_input())

li = []
for i in range(n):
    cmd = raw_input().split()
    if cmd[0] == 'insert':
        li.insert(0,cmd[1])
    elif cmd[0] == 'delete':
        try:
            li.remove(cmd[1])
    elif cmd[0] == 'deleteFirst':
        li.pop(0)
    elif cmd[0] == 'deleteLast':
        li.pop()
    print li
for e in li:
    print e,

Submission status: Runtime Error

Solution code:
import sys

A=[[0,0,0]]
size = 0

def insert(A,x):
    global size

    fp=A[0][1]
    try:
        i=[e[0] for e in A].index(-1)
        A[i]=[x,fp,0]
        A[fp][2]=i
        A[0][1]=i
    except:
        A.append([x,fp,0])
        A[fp][2]=len(A)-1
        A[0][1]=len(A)-1     
    size += 1    

def delete(A,x):
    global size
    p =A[0][1]
    while A[p][0]!=x:
        p=A[p][1]
        if p==0: return
    fp=A[p][1]
    bp=A[p][2]
    A[fp][2]=bp
    A[bp][1]=fp
    A[p]=[-1,-1,-1]
    size -= 1
    return

def deletefirst(A):
    global size
    if size == 0: return
    p=A[0][1]
    fp=A[p][1]
    A[0][1]=fp
    A[fp][2]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

def deletelast(A):
    global size
    if size == 0: return
    p=A[0][2]
    bp=A[p][2]
    A[0][2]=bp
    A[bp][1]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

n = int(raw_input())
for i in range(n):
    s = (raw_input().split())
    if s[0][0] == 'i':#'insert':
        insert(A,int(s[1]))
    elif len(s[0]) == 6;#'delete':
        delete(A,int(s[1]))
    elif s[0][7] == 'F':#'deleteFirst':
        deletefirst(A)
    elif s[0][7] == 'L':#'deleteLast':
        deletelast(A)

e = A[0][1]
while e!=0:
    print A[e][0],
    e = A[e][1]

Submission status: Runtime Error

Solution code:
import sys

A=[[0,0,0]]
buf=[]
size = 0

def insert(A,x):
    global size,buf
    fp=A[0][1]
    try:
        if buf==[]:
            buf = [i for i,e in enumerate(A) if e==-1]
        else:
            i = buf[-1]
            buf = buf[:-1]
        A[i]=[x,fp,0]
        A[fp][2]=i
        A[0][1]=i
    except:
        A.append([x,fp,0])
        A[fp][2]=len(A)-1
        A[0][1]=len(A)-1     
    size += 1    

def delete(A,x):
    global size
    p =A[0][1]
    while A[p][0]!=x:
        p=A[p][1]
        if p==0: return
    fp=A[p][1]
    bp=A[p][2]
    A[fp][2]=bp
    A[bp][1]=fp
    A[p]=[-1,-1,-1]
    size -= 1
    return

def deletefirst(A):
    global size
    if size == 0: return
    p=A[0][1]
    fp=A[p][1]
    A[0][1]=fp
    A[fp][2]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

def deletelast(A):
    global size
    if size == 0: return
    p=A[0][2]
    bp=A[p][2]
    A[0][2]=bp
    A[bp][1]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

while int(raw_input())
    s = (raw_input().split())
    if s[0] == 'insert':
        insert(A,s[1])
    elif s[0] == 'delete':
        delete(A,s[1])
    elif s[0] == 'deleteFirst':
        deletefirst(A)
    elif s[0] == 'deleteLast':
        deletelast(A)
    n -=1
    
e = A[0][1]
while e!=0:
    print A[e][0],
    e = A[e][1]

Submission status: Runtime Error

Solution code:
import sys

A=[[0,0,0]]
buf=[]
size = 0

def insert(A,x):
    global size,buf
    fp=A[0][1]
    try:
        if buf==[]:
            buf = [i for i,e in enumerate(A) if e==-1]
        else:
            i = buf[-1]
            buf = buf[:-1]
        A[i]=[x,fp,0]
        A[fp][2]=i
        A[0][1]=i
    except:
        A.append([x,fp,0])
        A[fp][2]=len(A)-1
        A[0][1]=len(A)-1     
    size += 1    

def delete(A,x):
    global size
    p =A[0][1]
    while A[p][0]!=x:
        p=A[p][1]
        if p==0: return
    fp=A[p][1]
    bp=A[p][2]
    A[fp][2]=bp
    A[bp][1]=fp
    A[p]=[-1,-1,-1]
    size -= 1
    return

def deletefirst(A):
    global size
    if size == 0: return
    p=A[0][1]
    fp=A[p][1]
    A[0][1]=fp
    A[fp][2]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

def deletelast(A):
    global size
    if size == 0: return
    p=A[0][2]
    bp=A[p][2]
    A[0][2]=bp
    A[bp][1]=0
    A[p]=[-1,-1,-1]
    size -= 1
    return 0

while int(raw_input()):
    s = (raw_input().split())
    if s[0] == 'insert':
        insert(A,s[1])
    elif s[0] == 'delete':
        delete(A,s[1])
    elif s[0] == 'deleteFirst':
        deletefirst(A)
    elif s[0] == 'deleteLast':
        deletelast(A)
    n -=1
    
e = A[0][1]
while e!=0:
    print A[e][0],
    e = A[e][1]

Submission status: Runtime Error

Solution code:
import sys

class Deque:
    # セルの定義
    class Cell2:
        def __init__(self, x, y = None, z = None):
            self.data = x
            self.next = y
            self.prev = z

    # 初期化
    def __init__(self):
        head = Deque.Cell2(None)  # ヘッダ
        head.next = head          # 循環リスト
        head.prev = head
        self.size = 0
        self.head = head

    # 先頭に追加
    def push_front(self, x):
        h = self.head
        q = h.next
        p = Deque.Cell2(x, q, h)
        h.next = p
        q.prev = p
        self.size += 1

    # 最後尾のデータを取り出す
    def pop_back(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.prev
        p = q.prev
        p.next = h
        h.prev = p
        self.size -= 1
        return q.data

    # 先頭のデータを取り出す
    def pop_front(self):
        if self.size == 0: raise IndexError
        h = self.head
        q = h.next
        p = q.next
        p.prev = h
        h.next = p
        self.size -= 1
        return q.data

    # xをもつセルを削除する
    def delete(self,x):
        h=self.head.next
        while h.data!=x:
            h=h.next
            if h==self.head: raise IndexError
        q=h.next
        p=h.prev
        q.prev=p
        p.next=q
        self.size -= 1
        return

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

Submission status: Runtime Error

Solution code:
import sys

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

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

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

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

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

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

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