Problem:

List

 

  For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor.

  
insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted element.

  
move($d$): Move the cursor to the end by $d$, if $d$ is positive. Move the cursor to the front by $d$, if $d$ is negative.

  
erase(): Delete the element indicated by the cursor. After this operation, the cursor points the element next to the deleted element. In case there is no such element, the cursor should point END.
  

  In the initial state, $L$ is empty and the cursor points END.

Input

  The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $d$

or

2

  where the first digits 0, 1 and 2 represent insert, move and erase operations respectively.

Output

  Print all elements of the list in order after performing given operations. Print an element in a line.

Constraints

  
$1 \leq q \leq 500,000$

  
The cursor indicates an element of $L$ or END during the operations

  
Erase operation will not given when the cursor points END

  
$-1,000,000,000 \leq x \leq 1,000,000,000$

  
Moving distance of the cursor ($\sum{|d|}$) does not exceed 1,000,000

  
$L$ is not empty after performing all operations

Sample Input 1

5
0 1
0 2
0 3
1 1
2

Sample Output 1

3
1



Sample input:
5
0 1
0 2
0 3
1 1
2


Sample output:
3
1

Submission status: Accepted

Solution code:
import sys

def input():
    return sys.stdin.readline().rstrip()

class Node:
    def __init__(self, value, prev_node, next_node):
        self.value = value
        self.prev_node = prev_node
        self.next_node = next_node

class LinkedList:
    def __init__(self):
        self.current_node = Node(None, None, None)
        self.front_node = self.current_node
        self.end_node = self.current_node

    def insert(self, value):
        current_node = self.current_node
        prev_node = current_node.prev_node
        if prev_node == None:
            newNode = Node(value, None, current_node)
            current_node.prev_node = newNode
            self.current_node = newNode
            self.front_node = newNode
        else:
            newNode = Node(value, prev_node, current_node)
            prev_node.next_node = newNode
            current_node.prev_node = newNode
            self.current_node = newNode

    def remove(self):
        prev_node = self.current_node.prev_node
        next_node = self.current_node.next_node
        if prev_node == None:
            next_node.prev_node = None
            self.front_node = next_node
            self.current_node = next_node
        else:
            next_node.prev_node = prev_node
            prev_node.next_node = next_node
            self.current_node = next_node

    def move(self, diff):
        if diff > 0:
            for _ in range(diff):
                self.current_node = self.current_node.next_node
        elif diff < 0:
            for _ in range(-diff):
                self.current_node = self.current_node.prev_node

    def print(self):
        node = self.front_node
        while node != self.end_node:
            print(node.value)
            node = node.next_node

input()
a = LinkedList()
while True:
    line = input()
    if not line:
        break
    if line[0] == '0':
        a.insert(int(line[2:]))
    elif line[0] == '1':
        a.move(int(line[2:]))
    else:
        a.remove()

a.print()

Submission status: Accepted

Solution code:
import collections


class CursorList():
    def __init__(self):
        self.vector = collections.deque()
        self.cursor = 0

    def insert(self, x):
        self.vector.appendleft(x)
        return self

    def move(self, d):
        self.vector.rotate(-d)
        self.cursor += d
        return self

    def erase(self):
        self.vector.popleft()
        return self


num_queue = int((input()))
L = CursorList()

for i in range(0, num_queue):
    queue = tuple(map(int, input().split(' ')))
    if queue[0] == 0:
        L.insert(queue[1])
    elif queue[0] == 1:
        L.move(queue[1])
    elif queue[0] == 2:
        L.erase()

L.vector.rotate(L.cursor)
print('\n'.join(map(str, L.vector)))

Submission status: Accepted

Solution code:
from collections import deque
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    n=int(input())
    sum_d=0
    aa=deque()
    for _ in range(n):
        qq=list(map(int, input().split()))
        if qq[0]==0:
            aa.appendleft(qq[1])
        elif qq[0]==1:
            aa.rotate(-qq[1])
            sum_d+=qq[1]
        else:
            aa.popleft()
    aa.rotate(sum_d)
    for a in aa:
        print(a)

main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

q = int(input())
L = deque()
L2 = deque()
cur = 0
for i in range(q):
    query = sys.stdin.readline()
    if query[0] == '0':
        L2.appendleft(query[2:].strip())
    elif query[0] == '1':
        n = int(query[2:].strip())
        if n > 0:
            for _ in range(n):
                L.append(L2[0])
                L2.popleft()
        else:
            for _ in range(-n):
                L2.appendleft(L[-1])
                L.pop()
    else:
        L2.popleft()

for i in L:
    print(i)
for i in L2:
    print(i)

Submission status: Accepted

Solution code:
from collections import deque
import sys

n=int(input())
A=deque()
cur=0
for i in range(n):
  S=input()
  if S[0]=='0':
    A.append(S[2:])
  elif S[0]=='1':
    A.rotate(int(S[2:]))
    cur-=int(S[2:])
  elif S[0]=='2':
    A.pop()
A.rotate(cur)
A.reverse()
print(*A, sep="\n")

Submission status: Accepted

Solution code:
from typing import List


class Node:
    __slots__ = ['prev', 'next', 'data']

    def __init__(self, prev, next, data) -> None:
        self.prev = prev
        self.next = next
        self.data = data


def insert(x: int, cur: Node) -> Node:
    cur.prev.next = cur.prev = cur = Node(cur.prev, cur, x)
    return cur


def move(x: int, cur: Node) -> Node:
    if x > 0:
        for _ in range(x):
            cur = cur.next
    else:
        for _ in range(-x):
            cur = cur.prev
    return cur


def erase(cur: Node) -> Node:
    cur.next.prev = cur.prev
    cur.prev.next = cur = cur.next
    return cur


if __name__ == "__main__":
    num_query = int(input())
    root = Node(None, None, None)
    cur = root.next = Node(root, None, None)

    for _ in range(num_query):
        op, *value = map(lambda x: int(x), input().split())
        if (0 == op):
            cur = insert(value[0], cur)
        elif (1 == op):
            cur = move(value[0], cur)
        elif (2 == op):
            cur = erase(cur)
        else:
            pass

    ans: List[int] = []
    it = root.next
    while it.next:
        ans.append(it.data)
        it = it.next

    for elem in ans:
        print(elem)

Submission status: Accepted

Solution code:
import sys

class DLLNode:
    __slots__ = ['prev', 'next', 'data']

    def __init__(self, prev, next, data):
        self.prev = prev
        self.next = next
        self.data = data

root = DLLNode(None, None, None)
cur = root.next = DLLNode(root, None, None)

def insert(x, cur):
    cur.prev.next = cur.prev = cur = DLLNode(cur.prev, cur, x)
    return cur

def move(x, cur):
    d = int(x)
    if d > 0:
        for _ in range(d):
            cur = cur.next
    else:
        for _ in range(-d):
            cur = cur.prev
    return cur

def erase(_, cur):
    cur.next.prev = cur.prev
    cur.prev.next = cur = cur.next
    return cur

C = {'0': insert, '1': move, '2': erase}
sys.stdin.readline()
for query in sys.stdin:
    cur = C[query[0]](query[2:], cur)

ans = []
it = root.next
while it.next:
    ans.append(it.data)
    it = it.next

sys.stdout.writelines(ans)

Submission status: Accepted

Solution code:
def solve():
    from sys import stdin
    f_i = stdin
    q = f_i.readline()
    d = 0
    
    from collections import deque
    L = deque()
    
    for l in f_i:
        if l[0] == '0':
            L.append(l[2:])
        elif l[0] == '1':
            r = int(l[2:])
            L.rotate(r)
            d -= r
        else:
            L.pop()
    L.rotate(d)
    L.reverse()
    print(''.join(L), end='')

solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Dynamic Arrays and List - List
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_1_C&lang=jp

"""

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

class Lst:
    def __init__(self):
        self.nil = Node('END')
        self.nil.next = self.nil
        self.nil.prev = self.nil
        self.cur = self.nil

    def insert(self, value):
        x = Node(value)
        x.prev = self.cur.prev
        self.cur.prev.next = x
        self.cur.prev = x
        x.next = self.cur
        self.cur = x

    def move(self, d):
        if d >= 0:
            for _ in range(d):
                self.cur = self.cur.next
        else:
            for _ in range(abs(d)):
                self.cur = self.cur.prev


    def erase(self):
        if self.cur == self.nil:
            return
        p = self.cur.next
        self.cur.prev.next = self.cur.next
        self.cur.next.prev = self.cur.prev
        self.cur = p


lst = Lst()
for _ in range(int(input())):
    op, n = (input() + ' 1').split()[:2]
    if op == '0':
        lst.insert(int(n))
    elif op == '1':
        lst.move(int(n))
    else:
        lst.erase()

cur = lst.nil
while cur.next != lst.nil:
    cur = cur.next
    print(cur.key)

Submission status: Accepted

Solution code:
from sys import stdin

class LinkedList():
    def __init__(self):
        self.head = [None, None, None]
        self.head[1] = self.pos = self.tail = [self.head, None, None]

    def insert(self, x):
        temp = [self.pos[0], self.pos, x]
        self.pos[0][1] = self.pos[0] = self.pos = [self.pos[0], self.pos, x]

    def move_right(self, d):
        for _ in range(d):
            self.pos = self.pos[1]

    def move_left(self, d):
        for _ in range(d):
            self.pos = self.pos[0]

    def move(self, d):
        if d > 0:
            self.move_right(d)
        else:
            self.move_left(d * -1)

    def erase(self):
        self.pos[1][0] = self.pos[0]
        self.pos = self.pos[0][1] = self.pos[1]

    def to_list(self):
        index = self.head[1]
        out = []
        while(index[1] is not None):
            out.append(index[2])
            index = index[1]
        return out

n = stdin.readline()
queries = stdin.readlines()
ll = LinkedList()
#count = 0
for query in queries:
    #print(count)
    #count += 1
    query = query.split()
    if query[0] == '0':
        ll.insert(query[1])
    elif query[0] == '1':
        ll.move(int(query[1]))
    else:
        ll.erase()

print('\n'.join(ll.to_list()))

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, val=None, prev=None, nextNode=None):
        self.val = val
        self.prev = prev
        self.nextNode = nextNode

class LinkedList():
    def __init__(self):
        self.end = Node('END')
        self.cursol_node = self.end
    
    def insertBefore(self, x):
        new_node = Node(val=x, prev=self.cursol_node.prev, nextNode=self.cursol_node)
        if self.cursol_node.prev != None:
            self.cursol_node.prev.nextNode = new_node
        #現在のカーソルノードのprevを新しいノードとリンク
        self.cursol_node.prev = new_node
        #新しいノードをカーソルノードとする
        self.cursol_node = new_node

    def move(self, d):
        if d > 0:
            for i in range(d):
                #ノードのnextがENDになるまでカーソルノードを移動
                if self.cursol_node.nextNode == None:break
                self.cursol_node = self.cursol_node.nextNode
        elif d < 0:
            for i in range(abs(d)):
                if self.cursol_node.prev == None:break
                self.cursol_node = self.cursol_node.prev

    def erase(self):
        if self.cursol_node != self.end:
            if self.cursol_node.prev != None:
                #前提条件としてcursolがENDにある状態でeraseは行われないため、prevのみNoneチェック
                self.cursol_node.prev.nextNode = self.cursol_node.nextNode
            self.cursol_node.nextNode.prev = self.cursol_node.prev
            self.cursol_node = self.cursol_node.nextNode
    
    def print_nodes_val(self):
        ans_list = []
        target_node = self.end
        while True:
            if target_node.prev == None:break
            else:
                target_node = target_node.prev
                ans_list.append(target_node.val)
        ans_list = ans_list[::-1]
        return ans_list

linkedList = LinkedList()
n = int(input())
for i in range(n):
    q,*x = map(int, input().split())
    x = x[0] if x else None
    if q == 0:
        linkedList.insertBefore(x)
    elif q == 1:
        linkedList.move(x)
    elif q == 2:
        linkedList.erase()
print('\n'.join(map(str,linkedList.print_nodes_val())))

Submission status: Accepted

Solution code:
class Node:
    __slots__ = ["val", "prev", "next"]

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


class DoublyLinkedList():
    def __init__(self):
        self.end = Node(val="END", prev=None, next=None)
        self.cur = self.end

    def insert(self, x):
        new_node = Node(val=x, prev=self.cur.prev, next=self.cur)

        if self.cur.prev != None:
            self.cur.prev.next = new_node
        self.cur.prev = new_node
        self.cur = new_node

    def move(self, d):
        if d > 0:
            for i in range(d):
                if self.cur.next == None:
                    break
                self.cur = self.cur.next
        elif d < 0:
            for i in range(abs(d)):
                if self.cur.prev == None:
                    break
                self.cur = self.cur.prev
        else:
            raise
    
    def erase(self):
        if self.cur == self.end:
            return

        if self.cur.prev != None:
            self.cur.prev.next = self.cur.next

        self.cur.next.prev = self.cur.prev
        self.cur = self.cur.next

    def print_elements(self):
        node_list = []
        crnode = self.end
        while True:
            if crnode.prev == None:
                break
            node_list.append(crnode.prev.val)
            crnode = crnode.prev
        for i in range(len(node_list)-1, -1, -1):
            print(node_list[i])



def main():

    q = int(input())

    L = DoublyLinkedList()

    for _ in range(q):
    
        command, *list_num = input().split()
    
        if   command == "0":
            # insert(x)
            x = int(list_num[0])
            L.insert(x)
        elif command == "1":
            # move(d)
            d = int(list_num[0])
            L.move(d)
        elif command == "2":
            # erase()
            L.erase()
        else:
            raise


    L.print_elements()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, left, right, date):
        self.left = left
        self.right = right
        self.date = date

root = Node(None, None, None)
cur = root.right = Node(root, None, None)

def insert(x, cur):
    cur.left.right = cur.left = cur = Node(cur.left,cur, x)
    return cur

def move(x, cur):
    d = int(x[0])
    if d > 0:
        for _ in range(d):
            cur = cur.right
    else:
        for _ in range(-d):
            cur = cur.left
    return cur

def erase(_,cur):
    cur.right.left = cur.left
    cur.left.right = cur.right
    cur = cur.right
    return cur

C = {'0':insert, '1':move, '2':erase}
n = int(input())
for _ in range(n):
    query = input().split()
    cur = C[query[0]](query[1:], cur)

ans = []
it = root.right
while it.right:
    ans.append(it.date)
    it = it.right

for i in range(len(ans)):
    print(ans[i][0])

Submission status: Accepted

Solution code:
from sys import stdin

class QueueNode(object):
	def __init__(self,data,next=None,prev=None):
		self.data = data
		self.next = next
		self.prev = prev

class LinkList(object):
	def __init__(self,head=None):
		self.head = head
		self.tail = head
		self.cur  = head

	def insert_q(self,data):
		node = QueueNode(data)

		if self.cur is None:
			self.head = node
			self.tail = node
			self.cur  = node
			return

		currentNode = self.cur
		preNode = currentNode.prev

		if currentNode.prev is None:
			currentNode.prev = node
			node.next = currentNode
			self.head = self.cur = node
		else:
			if self.tail is not None:
				currentNode.prev = node
				node.prev = preNode
				node.next = currentNode
				preNode.next = node
				self.cur = node
			else:
				currentNode.next = node
				node.prev = currentNode
				node.next = None
				self.cur = node
				self.tail = node


	def move_q(self,mv):
		currentNode = self.cur
		cnt = mv
		while cnt != 0:
			if mv < 0:#prev
				if currentNode.prev is None:
					self.head = self.cur = currentNode
					break
				else:
					currentNode = currentNode.prev
					self.cur = currentNode
					cnt += 1
			else:#next
				if currentNode.next is None:
					self.cur = currentNode
					break
				else:
					currentNode = currentNode.next
					self.cur = currentNode
					cnt -= 1


	#カレントを削除する
	def delete_q(self):
		currentNode = self.cur
		nexNode = currentNode.next
		preNode = currentNode.prev

		#自身の前がいない（=先頭）
		if preNode is None:
			nexNode.prev = None
			self.head = nexNode
			self.cur = nexNode
		#自身の後ろがいない（=末尾）
		elif nexNode is None:
			preNode.next = None
			self.tail = None
		else:
			preNode.next = currentNode.next
			nexNode.prev = currentNode.prev
			self.cur = currentNode.next

	#先頭を表示する
	def print_q(self):
		if self.head is not None:
			print(self.head.data)

	#全体表示（先頭から）
	def print_all(self):
		if self.head is not None:
			currentNode = self.head
			while currentNode.next is not None:
				print(currentNode.data)
				currentNode = currentNode.next

if __name__ == '__main__':

	loopnum = int(input())

	ll = LinkList()
	ll.insert_q("E")
	for i in range(loopnum):
		cmd = stdin.readline().strip().split()
		if cmd[0] == "0":
			t = int(cmd[1])
			ll.insert_q(t)
		elif cmd[0] == "1":
			t = int(cmd[1])
			ll.move_q(t)
		else:
			ll.delete_q()
	ll.print_all()

Submission status: Accepted

Solution code:
q = int(input())
A = [0 for i in range(1500000)]
A[0] = 'end'
cursor = 0
head = [0 for i in range(1500000)]
head_len = 0

def insert(x):
	global cursor
	cursor += 1
	A[cursor] = x
def move(d):
	global cursor, head, head_len
	if d >= 0:
		head[head_len-1+d+(1): head_len-1+(1):-1] = A[cursor-d+1:cursor+1]
	else:
		A[cursor+1:cursor+1+(-d)] = head[head_len-1+(1):head_len-(-d)-1+(1):-1]
	cursor -= d
	head_len += d
def erase():
	global cursor
	cursor -= 1

for i in range(q):
	a = input()
	if a != "2":
		b = [int(i) for i in a.split()]
		if b[0] == 0:
			insert(b[1])
		elif b[0] == 1:
			move(b[1])
	else:
		erase()
	#print(A[:cursor+1],head[1:1+head_len][::-1])

A[cursor+1:cursor+1+head_len] = head[head_len-1+(1):-1+(1):-1]
length = cursor +  head_len
for i in range(1,length+1)[::-1]:
	print(A[i])

Submission status: Accepted

Solution code:
cursor = 0
n = int(input())

class LinkedList():
    class Cell():
        def __init__(self,val,pre,post):
            self.val = val
            self.pre = pre
            self.post = post

    def __init__(self):
        self.cursor = LinkedList.Cell(None,None,None)
        
    def insert(self,val):
        temp = self.cursor
        self.cursor = LinkedList.Cell(val,temp.pre,temp)
        if temp.pre != None:
            temp.pre.post = self.cursor
        temp.pre = self.cursor
        
        
            

    def move(self,d):
        if d > 0:
            for i in range(d):
                self.cursor = self.cursor.post
                
        else:
            
            for i in range(-d):
                
                self.cursor = self.cursor.pre
            
    def remove(self):
        temp = self.cursor
        tpos = temp.post
        
        if temp.pre != None:
            tpre = temp.pre
            tpre.post = tpos
            tpos.pre = tpre
        else:
            tpos.pre = None
        del temp
        self.cursor = tpos
        
    def moveToTop(self):
        while self.cursor.pre != None:
            self.cursor = self.cursor.pre

linkedList = LinkedList()

for i in range(n):
    a = [int(j) for j in input().split()]
    if a[0] == 0:
        linkedList.insert(a[1])
    elif a[0] == 1:
        linkedList.move(a[1])
    elif a[0] == 2:
        linkedList.remove()

linkedList.moveToTop()
print(linkedList.cursor.val)
while linkedList.cursor.post.val != None:
    linkedList.cursor = linkedList.cursor.post
    print(linkedList.cursor.val)

Submission status: Accepted

Solution code:
import sys


class Node:
    __slots__ = ['prev', 'next', 'id', 'val']

    def __init__(self, prev_node, next_node, id, val):
        self.prev = prev_node
        self.next = next_node
        self.id = id
        self.val = val

    def __repr__(self):
        return f'{self.id},{self.val}'


class LinkedList:
    def __init__(self):
        begin_node = Node(None, None, 0, -sys.maxsize)
        end_node = Node(None, None, 1, sys.maxsize)
        begin_node.next = end_node
        end_node.prev = begin_node
        self.Nodes = {0: begin_node, 1: end_node}
        self.id = 2
        self.cursor = self.Nodes[1]

    def move(self, d):
        if d < 0:
            for i in range(abs(d)):
                self.cursor = self.cursor.prev
        elif d > 0:
            for i in range(abs(d)):
                self.cursor = self.cursor.next

    def print_all_node(self):
        out = ''
        while self.cursor.prev is not None:
            self.cursor = self.cursor.prev

        self.cursor = self.cursor.next
        while self.cursor.next is not None:
            out += f'{self.cursor.val}\n'
            self.cursor = self.cursor.next
        print(out, end='')

    def insert(self, val):
        tmp_node = Node(self.cursor.prev, self.cursor, self.id, val)
        self.cursor.prev.next = tmp_node
        self.cursor.prev = tmp_node
        self.Nodes[self.id] = tmp_node
        self.cursor = tmp_node
        self.id += 1

    def erase(self):
        self.cursor.prev.next = self.cursor.next
        self.cursor.next.prev = self.cursor.prev
        del self.Nodes[self.cursor.id]
        self.cursor = self.cursor.next


linkedlist = LinkedList()


nq = int(input())
lines = sys.stdin.readlines()
for i in range(nq):
    query, *arg = lines[i].split()
    #print(query,arg)
    if query == '0':  # insert x
        linkedlist.insert(arg[0])
    elif query == '1':  # move d
        linkedlist.move(int(arg[0]))
    elif query == '2':  # erase
        linkedlist.erase()
    else:
        raise AssertionError

linkedlist.print_all_node()

Submission status: Accepted

Solution code:
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_1_C&lang=jp
# List

from collections import deque
#import cProfile
#import time
import sys

input = sys.stdin.readline

def loop_proc():
    q1 = deque()
    q2  = deque()
    l2 = []
    cur = 0
    rflag = True
    n = int(input())
    cnt = 0

    while (cnt < n):
        cnt += 1
        if (rflag == True):
            l = list(map(int,input().split()))
        else:
            l = l2
        c = l[0]
        rflag =True
        #追加する場合
        if ( c == 0 ):
            d = l[1]
            #APPEND() & POP()は読み飛ばす
            if (cnt < n ):
                l2 = list(map(int,input().split()))
                if (l2[0] == 2 ):
                    cnt += 1
                    continue
                rflag =False
            q1.append(d)
        #カーソル移動の場合
        elif(c == 1):

            cur = l[1]
            if cur <  0 :
                for i in range(abs(cur)):
                    q1.append(q2.pop())
            else:
                for i in range(abs(cur)):
                    q2.append(q1.pop())
#            print (q1,q2)
        #要素削除の場合
        elif(c == 2):
            q1.pop()

    while len(q2) != 0 :
        print (q2.popleft())
    while len(q1) != 0 :
        print (q1.pop())

#    for i in wl:
#        print (i)
loop_proc()
#pr = cProfile.Profile()
#pr.enable()
#pr.runcall(loop_proc)
#pr.print_stats()

Submission status: Accepted

Solution code:
import sys


class DLLNode:
    __slots__ = ['prev', 'next', 'data']

    def __init__(self, prev, next, data):
        self.prev = prev
        self.next = next
        self.data = data


root = DLLNode(None, None, None)
cur = root.next = DLLNode(root, None, None)


def insert(x, cur):
    cur.prev.next = cur.prev = cur = DLLNode(cur.prev, cur, x)
    return cur


def move(x, cur):
    d = int(x)
    if d > 0:
        for _ in range(d):
            cur = cur.next
    else:
        for _ in range(-d):
            cur = cur.prev
    return cur


def erase(_, cur):
    cur.next.prev = cur.prev
    cur.prev.next = cur = cur.next
    return cur


C = {'0': insert, '1': move, '2': erase}
sys.stdin.readline()
for query in sys.stdin:
    cur = C[query[0]](query[2:], cur)

ans = []
it = root.next
while it.next:
    ans.append(it.data)
    it = it.next

sys.stdout.writelines(ans)

Submission status: Accepted

Solution code:
readline = open(0).readline
writelines = open(1, 'w').writelines

Q = int(readline())
root = [None, None, None]
cursor = root[1] = [root, None, None]
def insert(x):
    global cursor
    cursor[0][1] = cursor[0] = cursor = [cursor[0], cursor, x]
def move(d):
    global cursor
    if d > 0:
        for _ in range(d):
            cursor = cursor[1]
    else:
        for _ in range(-d):
            cursor = cursor[0]
def erase():
    global cursor
    cursor[1][0] = cursor[0]
    cursor[0][1] = cursor = cursor[1]


C = [insert, move, erase].__getitem__
for q in range(Q):
    t, *a = map(int, readline().split())
    C(t)(*a)
root = root[1]
ans = []
while root[1]:
    ans.append("%d\n" % root[2])
    root = root[1]
writelines(ans)

Submission status: Accepted

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

class LinkedList():
    def __init__(self, val):
        self.val = val
        self.prev = None
        self.next = None

    def insert(self, cursor):
        #print('Insert, new cursor', self.val)
        self.prev = cursor.prev
        if self.prev: self.prev.next = self
        self.next = cursor
        cursor.prev = self
        #self.print_list()
        return self

    def remove(self):
        #print('Remove', self.val, 'new cursor', self.next.val)
        if self.prev:
            self.prev.next = self.next
        self.next.prev = self.prev
        #self.print_list()
        return self.next

    def move(self, count):  # cursor is passed
        #print('Moving', count, end = ' ')
        #self.print_list()
        cursor = self
        while count > 0:
            cursor = cursor.next
            count -= 1
        while count < 0:
            cursor = cursor.prev
            count += 1
        #print('new cursor', cursor.val)
        return cursor

    def print_list(self):
        top = self
        while top.prev != None:
            top = top.prev
        while top:
            print(top.val, end = ' ')
            top = top.next
        print()


import sys
cursor = LinkedList(None) 

num_tc = int(sys.stdin.readline())
for i in range(num_tc):
    q = list(map(int, sys.stdin.readline().split()))
    if q[0] == 0:
        elem = LinkedList(q[1])
        cursor = elem.insert(cursor)
    elif q[0] == 1:
        cursor = cursor.move(q[1])
    elif q[0] == 2:
        cursor = cursor.remove()
    else:
        raise ValueError

top = cursor
while top.prev != None:
    top = top.prev

while top.val!=None:
    print(top.val)
    top = top.next

Submission status: Runtime Error

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

class DoublyLinkedList():
    def __init__(self, cur=None):
        self.num = 0
        self.cur = cur
        self.first = cur

    def insert(self, x):
        if self.cur == None:
            self.cur = Node(x, None, None)
            self.first = self.cur
        else:
            prev = self.cur.prev
            new_node = Node(x, prev, self.cur)
            if prev != None: prev.next = new_node
            self.cur.prev = new_node
            self.cur = new_node
        self.__set_first()

    def move(self, d):
        if d > 0:
            for i in range(d):
                self.cur = self.cur.next
        elif d < 0:
            for i in range(abs(d)):
                self.cur = self.cur.prev

    def erase(self):
        if self.cur.next == None:
            self.cur = self.cur.prev
            if self.cur != None: self.cur.next = None
        else:
            if self.cur.prev != None: self.cur.prev.next = self.cur.next
            self.cur.next.prev = self.cur.prev
            self.cur = self.cur.next
        self.__set_first()

    def __set_first(self):
        if self.cur != None and self.cur.prev == None:
            self.first = self.cur

    def print_elements(self):
        node = self.first
        while True:
            if node == None: break
            print(node.val)
            node = node.next

dll = DoublyLinkedList()
q = int(input())
for i in range(q):
    op = list(map(int, input().split(' ')))
    if op[0] == 0:
        dll.insert(op[1])
    elif op[0] == 1:
        dll.move(op[1])
    elif op[0] == 2:
        dll.erase()

dll.print_elements()

Submission status: Runtime Error

Solution code:
N = int(raw_input())
A = map(int,raw_input().split())
print ' '.join(map(str,A))
for i in range(1,N):
    v = A[i]
    j = i - 1
    while j >=0 and A[j] > v:
        A[j+1] = A[j]
        j -= 1
    A[j+1] = v
    print ' '.join(map(str,A))

Submission status: Runtime Error

Solution code:

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


def run():
    n = int(input())
    tail = Node(None)
    node = tail
 
    for _ in range(n):
        command = input()
        if command.startswith('0'):
            nn = Node(int(command[2:]))
            nn.prev, nn.next = node.prev, node
            if node.prev is not None:
                node.prev.nex
't = nn
            node.prev = nn
            node = node.prev
        elif command.startswith('1'):
            i = int(command[2:])
            if i > 0:
                for _ in range(i):
                    node = node.next
            else:
                for _ in range(-i):
                    node = node.prev
        elif command.startswith('2'):
            p, n = node.prev, node.next
            node.prev, node.next = None, None
            node = n
            if p is None:
                n.prev = None
            else:
                n.prev, p.next = p, n
        else:
            raise ValueError('invalid command')
 
    st = []
    node = tail.prev
    while node is not None:
        st.append(node.value)
        node = node.prev
 
    while len(st) > 0:
        print(st.pop())
 
 
if __name__ == '__main__':
    run()

Submission status: Runtime Error

Solution code:
# coding=utf-8

A = []
cursor = 0

N = int(input())
for i in range(N):
    query = map(int, input().split())
    if query[0] == 0:
        A.insert(cursor, query[1])
    elif query[0] == 1:
        cursor += query[1]
    elif query[0] == 2:
        A.pop(cursor)
[print(x) for x in A]