class Node:
def __init__(self, item):
self.data = item
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.nodeCount = 0
self.head = Node(None)
self.tail = Node(None)
self.head.prev = None
self.head.next = self.tail
self.tail.prev = self.head
self.tail.text = None
def getLength(self): # 길이 얻어내기
return self.nodeCount
def traverse(self): # 리스트 순회
result = []
curr = self.head
while curr.next.next:
curr = curr.next
result.append(curr.data)
return result
def reverse(self): # 리스트 역순회
result = []
curr = self.tail
while curr.prev.prev:
curr = curr.prev
result.append(curr.data)
return result
def getAt(self, pos):
if pos < 1 or pos > self.nodeCount:
return None
if pos > self.nodeCount // 2:
i = 0
curr = self.tail
while i < self.nodeCount - pos + 1:
i += 1
curr = curr.prev
return curr
else:
i = 0
curr = self.head
while i < pos:
i += 1
curr = curr.next
return curr
def insertAfter(self, prev, newNode): # 특정 원소 삽입
next = prev.next
newNode.prev = prev
newNode.next = next
prev.next = newNode
next.prev = newNode
self.nodeCount += 1
return True
def insertBefore(self, next, newNode): # 특정 원소 삽입
prev = next.prev
newNode.prev = prev
newNode.next = next
prev.next = newNode
next.prev = newNode
self.nodeCount += 1
return True
def insertAt(self, pos, newNode): # 특정 원소 삽입
if pos < 1 or pos > self.nodeCount+1:
return False
prev = self.getAt(pos-1)
return self.insertAfter(prev, newNode)
def popAfter(self, prev): # 특정 원소 삭제
curr = prev.next
next = curr.next
prev.next = next
next.prev = prev
self.nodeCount -= 1
return curr.data
def popBefore(self, next): # 특정 원소 삭제
curr = next.prev
prev = curr.prev
next.prev = prev
prev.next = next
self.nodeCount -= 1
return curr.data
def popAt(self, pos): # 특정 원소 삭제
if pos < 1 or pos > self.nodeCount:
return None
prev = self.getAt(pos-1)
return self.popAfter(prev)
def concat(self, L): # 두 리스트 합치기
self.tail.prev.next = L.head.next
if L.nodeCount:
self.tail = L.tail
self.nodeCount += L.nodeCount
댓글남기기