💡 파이썬에서 연결리스트 문제는 연결리스트, deque, list로 풀 수 있다.

<시간 초과 코드>
import sys
from collections import deque
input = sys.stdin.readline
left = deque(input().rstrip())
right = deque()
M = int(input())
result = ''
for _ in range(M):
command = input().rstrip()
if command[0] == 'L' and left:
right.append(left.pop())
elif command[0] == 'D' and right:
left.append(right.pop())
elif command[0] == 'B' and left:
left.pop()
elif command[0] == 'P':
left.append(command[2])
for i in left:
result += ''.join(i)
for j in reversed(right):
result += ''.join(j)
print(result)
<정답 코드>
import sys
from collections import deque
input = sys.stdin.readline
left = deque(input().rstrip())
right = deque()
M = int(input())
result = ''
for _ in range(M):
command = input().rstrip()
if command[0] == 'L' and left:
right.append(left.pop())
elif command[0] == 'D' and right:
left.append(right.pop())
elif command[0] == 'B' and left:
left.pop()
elif command[0] == 'P':
left.append(command[2])
# 시간 단축을 위해 extend() 사용
reversedRight = reversed(right)
left.extend(reversedRight)
print(''.join(left))
<Linked List를 직접 구현해서 푼 코드>
import sys
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def append(self,val):
new_Node = ListNode(val)
if self.head is None:
self.head = new_Node
else:
curr = self.head
while curr.next != None:
curr = curr.next
curr.next = new_Node
def get(self,idx):
curr = self.head
for i in range(idx):
curr = curr.next
return curr.val
def insert(self, idx, val):
new_Node = ListNode(val)
curr = self.head
if idx == 0:
new_Node.next = curr
self.head = new_Node
else:
for i in range(idx-1):
curr = curr.next
new_Node.next = curr.next
curr.next = new_Node
def remove(self,idx):
if idx == 0:
self.head = self.head.next
return
curr = self.head
target = self.head
for i in range(idx-1):
target = target.next
for j in range(idx):
curr = curr.next
target.next = curr.next
def print_all(self):
curr = self.head
while curr is not None:
print(curr.val, end="")
curr = curr.next
print()
input = sys.stdin.readline
word = list(input().rstrip())
linkList = LinkedList()
for i in word:
linkList.append(i)
M = int(input())
cursor = len(word)
for _ in range(M):
command = list(input().rstrip())
if len(command) > 1:
linkList.insert(cursor,command[2])
cursor += 1
else:
if command[0] == 'L' and cursor > 0:
cursor -= 1
elif command[0] == 'D' and cursor < len(word)+1:
cursor += 1
elif command[0] == 'B' and cursor > 0:
linkList.remove(cursor)
cursor -= 1
print(cursor)
linkList.print_all()
linkList.print_all()