0% found this document useful (0 votes)
3 views

Data Structure and Algorithms (005) Fall 2024 - Week 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Data Structure and Algorithms (005) Fall 2024 - Week 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Data Structure

Fall 2024
Instructor: Prof. John Yun
Lecture: 9-12P, Wednesdays; S2-402

Department of AI  Big Data


Woosong University
Office Hours

When: Every Wednesdays from 2:00pm to 5:00pm

Where: Endicott College W19-225 (Prof. John Yun’s Office)

How: Only By Appointment via email to [email protected]

Duration: Maximum 30 minutes per student


HW Submission Guidelines
• Submit your homework assignment in MS Word document and
upload it into the LMS
• For programming assignments, please upload also your Python
program file with the .py extension into the LMS. Any program that
fails to run will receive no credit.
• Name your homework MS Word document as follows:
• HW2-[Your Student ID].docx
• Insert your images and screenshots of your Python program directly
into the MS Word document
• Please do not paste text directly into the LMS
• Please do not submit a PDF file
• Late submission will receive 0 point.

• Homework Grading: Correct # of Questions / Total = NN %


• [1]: Correct
• [0]: Wrong
• [0.3]: Partial credit
• List
• Array List (Python Built-in List)
• Linked List
• Array List vs. Linked List
• Improvement and
Expansion for Linked List
List

Week 4
Fall 2024
List
• Data arranged in a line or Data lined up.
ADT (Abstract Data Type)
• List of tasks that represents the type of data
being processed

• Without worrying about implementation


details

• Define data types at an abstract level

• Focusing on 'how to use it' rather than 'how


to implement it
Action of List
• Insert element x in the ith position
• Delete ith element
• Delete element x
• Informs ith element
• Informs which position the element x is
• Informs the size (total number of the elements) of the
array

 A data structure is also a data type


List Implementation
• List implemented in an Array

10 35 40 17 95 50 48 33 9

• List implemented in an Linked Array

10 17 35 40 55
• List
• Array List (Python Built-in List)
• Linked List
• Array List vs. Linked List
• Improvement and
Expansion for Linked List
Array List
(Python Built-in List)

Week 4
Fall 2024
List (array list) Object Structure
insert(i, x) Insert element x into ith position

append(x) Add element x to the end of the list


pop(i) Delete ith element x from list and inform

remove(x) Delete first element x from list

index(x) Inform the position of the element x

clear() Clears the list


count(x) Informs how many element x are in list
extend(a)) Expand and add object (e.g., a list) to list

copy() Copy the list


reverse() Reverse the order of the list

sort() Sort the elements in the list


Insert

3rd element 8th element

insert(3,77)

3rd element 8th element

Example of shifting elements after inserting an element into an array


Example of the Worst Insertion Efficiency
a[0] a[8]

a[ ] 10 35 40 17 95 50 48 33 9

First
0번 Element
원소 8th번element
원소 len(a): 9

insert(0, 77)

a[0] a[9]

a[ ] 77 10 35 40 17 95 50 48 33 9

First
0번 원소 Element 8th9번
element
원소 len(a): 10
Example of the Best Insertion Efficiency
a[8]

a[ ] 10 35 40 17 95 50 48 33 9

8th
8번 element
원소 len(a): 9

append(77)
a[9]

a[ ] 10 35 40 17 95 50 48 33 9 77

99th번element
원소 len(a): 10
Delete

3rd element 8th element

3rd element 7th element

Example of shifting elements after deleting an element from an array


3 Ways to Delete the Last item
a[0] a[3] A[8]

a[ ] 10 35 40 17 95 50 48 33 9

33rd번element
원소 8th 8element
번 원소 len(a): 9

pop() or pop(8), or pop(-1)


a[7]

a[ ] 10 35 40 17 95 50 48 33

3rd3번
element len(a): 8
원소 7th7element
번 원소
How to use the method
 Element Insertion

 Element Deletion
How to use the method
 Other Tasks
Limitation of Python Built-in List
• Underneath is implemented as an array
• Disadvantages of arrays
• Since elements are stored in contiguous space, insertions and deletions require
shifting operations.
• Since the size must be predetermined, an overflow requires reallocating the array
and copying the contents.
• But, in Python, it is managed automatically, so users don't need to worry
about it.

3rd element 8th element 3rd element

Allocation of new Array and Copying of the Whole

3rd element 7th element


Example of shifting elements after deleting an element from an array
Example of copying all elements to a new array when an insertion is
attempted and the array is full
• List
• Array List (Python Built-in List)
• Linked List
• Array List vs. Linked List
• Improvement and
Expansion for Linked List
Linked List

Week 4
Fall 2024
Linked List Object Structure

All you need is the reference to the


starting node of the Linked List


Node object Node object Node object

Linked List

Linked List Object


Meaning of each task

__head Reference to the first node

__numItems Total number of elements contained in the list

get(i) Informs the ith element in the linked list


isEmpty() Informs if the linked list is empty

size() Informs the total number of elements in the linked list

extend(a)) Expand and add object (e.g., a list, a tuple) to list


copy() Copy the list and returns the copied list
ListNode Object Structure

Typically drawn this way

item next

class ListNode:
def __init__(self, newItem, nextNode:'ListNode'):
self.item = newItem
self.next = nextNode

Node Class
Usage Example of ListNode Class
Head Node
• Linked Lists usually contains the reference(i.e. head) to
the first node None

10 17 35 40
head item next item next item next item next

head = ListNode(10, None) 10


head item next

head.next = ListNode(17, None) 10 17


head item next item next

 Here, head is a simple reference variable


Core Operation
Linked List of Integers
10 17 35 40 55

Insertion
10 17 35 40 55

25

Deletion
10 17 25 35 40 55
Typical Form
Representative Form
10 17 35 40 55

head

Initial State

Value of _ _head is None


head

General Form of the Linked List


Insertion Insert a new node after prev

0th 1st 2nd


10 17 35 40 55

head prev insert(2, 25)

10 17 35 40 55

25

head prev

newNode

Example of inserting element 25 in the middle of the linked list


No problem Inserting in the middle or at the end
Insert() But, inserting in the front doesn’t work.

newNode.item ← x prev
newNode.next ← prev.next
prev.next ← newNode …
_ _numItems += 1
x
newNode

Insertion in the Middle: Okay Insertion at the end: Okay

Example of inserting element 60 at the end


Example of inserting element 25 in the middle
Expression prev.next cannot be used when
newNode.item ← x Inserting an element at the front because prev
newNode.next ← head doesn’t exist
head ← newNode
numItems++ head

x
newNode

Example of inserting element 5 at the front of the linked list


Inserting an element into a linked list

Considering both of the


previous cases

Because of the infrequent occurrence of 'inserting at the front,'


do we always have to handle it by dividing into two cases like this?

There is a way to handle with one method → dummy head node


Linked List with the Dummy Head
Representative Form
dummy head
10 17 35 40 55

head

Initial State
dummy head

head
Insert(): The version with a dummy head

Example of inserting element at the front of the linked list with the
dummy head

Inserting an element into a linked list (with Dummy Head) If there is a dummy head,
all insertions will satisfy
because prev always exists.
append()
Inserting element x at the end

newNode.item ← x When prev is defined,


newNode.next ← prev.next
prev.next ← newNode
The code is the same
_ _numItems += 1 as the insert()
Deletion Deletes the node that follows prev

Example of deleting the element 35 from the linked list


pop() Removing the first
prev.next ← node does not work
prev.next.next
numItems--
prev

Deleting a node in the middle: Okay Deleting the node at the end: Okay

Example of deleting the element 35 from the linked list Example of deleting an element at the end
head

head ← head.next Expression prev.next cannot be used when


__numItems –= 1 deleting an element at the front because prev
doesn’t exist
Deleting an element from a linked list

Considering both of the


previous cases

Because of the infrequent occurrence of ‘deleting at the front,'


do we always have to handle it by dividing into two cases like this?

Indeed, having a dummy head allows it to handled as one case


3 examples of deleting element from the linked list with the dummy head

Deleting the element x from a linked list (with dummy head) If you have the dummy head,
this is enough because prev
always exists
Miscellaneous Tasks
Informs if the list is empty

Informs the ith element in the linked list

Informs the total number of


elements

Cleans the list


dummy head node

Informs the ith positioned node in the linked list

Informs the ordered position of the x in the linked list

dummy head

when x doesn’t exist


Linked List Class Structure
When the class ListNode is in a different file
Python Code (Insertion)
def __getNode(self, i:int) -> ListNode:
def insert(self, i:int, x): curr = self.__head # dummy head, index: -1
if i >= 0 and i <= self. __numItems: for index in range(i+1):
prev = self.__getNode(i - 1) curr = curr.next
newNode = ListNode(x, prev.next) return curr
prev.next = newNode
self.__numItems += 1
else:
Handle
print("index", i, ": out of bound in insert()") # 필요 시 에러 Error
처리

Inserting an element to the linked list (with dummy head)

Core Section (Similar Code)

Example of inserting an element to the front of the linked list with


the dummy head
Adding an element at the end
def append(self, newItem):
prev = self.__getNode(self.__numItems - 1)
newNode = ListNode(newItem, prev.next)
prev.next = newNode
self.__numItems += 1

Inserting an element to the linked list (with dummy head)

Core Section (Similar Code)


Python Code (deletion)
def pop(self, i:int): # i번 노드ith삭제
Delete node
if (i >= 0 and i <= self.__numItems-1):
prev = self.__getNode(i - 1)
curr = prev.next
prev.next = curr.next
retItem = curr.item
self.__numItems -= 1
return retItem
else:
return None

Deleting the element x from the linked list (with dummy


head)

Core Section(Similar Code)

3 examples of deleting element from the linked list with the dummy head
def remove(self, x): def __findNode(self, i:int) -> (ListNode, ListNode):
(prev, curr) = self.__findNode(x) prev = self.__head # dummy head
if curr != None: curr = prev.next # 0번 노드
Node #0
prev.next = curr.next while curr != None:
self.__numItems -= 1 if curr.item == x:
return x return (prev, curr)
else: else:
return None prev = curr; curr = curr.next
return (None, None)

Deleting the element x from the linked list


(with dummy head)

Core Section (Similar Code)


Python Code (Miscellaneous Tasks)

def get(self, i:int): def isEmpty(self) -> bool:


if self.isEmpty(): return self.__numItems == 0
return None
if (i >= 0 and i <= self.__numItems - 1): def size(self) -> int:
return self.__getNode(i).item return self.__numItems
else:
return None def clear(self):
self.__head = ListNode("dummy", None)
def index(self, x) -> int: self.__numItems = 0
curr = self.__head.next # 0번 Node
노드 #0:: 더미
Node 헤드
after the
다음 dummy
노드head
for index in range(self.__numItems): def count(self, x) -> int:
if curr.item == x: cnt = 0
return index curr = self.__head.next # 0번Node
노드 #0
else: while curr != None:
curr = curr.next if curr.item == x:
return -12345 # 안쓰는 Index 인덱스
not being used cnt += 1
curr = curr.next
return cnt
def extend(self, a): # 여기서
Here aahas
는 self
the 와 같은
same 타입의
type 리스트
of list as the self
def sort(self) -> None:
for index in range(a.size()): a = []
self.append(a.get(index)) for index in range(self.__numItems):
a.append(self.get(index))
def copy(self): a.sort()
a = LinkedListBasic() for index in range(len(a)):
for index in range(self.__numItems): self.append(a[index])
a.append(self.get(index))
return a

def reverse(self):
a = LinkedListBasic()
for index in range(self.__numItems):
a.insert(0, self.get(index))
self.clear()
for index in range(a.size()):
self.append(a.get(index))

def printList(self):
curr = self.__head.next # 0번 노드
Node #0:: 더미 헤드the
Node after 다음 노드head
dummy
while curr != None:
print(curr.item, end=" ")
curr = curr.next
print()
• List
• Array List (Python Built-in List)
• Linked List
• Array List vs. Linked List
• Improvement and
Array List Expansion for Linked List
vs.
Linked List

Week 4
Fall 2024
Array List
• Intuitively Name
• If an index is given, it can be accessed immediately (in constant time)
• Stored in contiguous space, so shifting operations are required for insertion or deletion.
• Since the size must be predetermined, in the case of overflow, the array needs to be
reallocated and the contents copied.
• Efficiency decreases with larger arrays.

3rd element
3rd element 8th element

Allocation of new Array and Copying of the Whole

3rd element 7th element


Example of copying all elements to a new array when an insertion is
Example of shifting elements after inserting an element into an array
attempted and the array is full
Linked List
• Stored in non-contiguous space, requiring the management of links
• Accessing by index still involves the overhead of following links.
• Insertion or deletion does not require shifting operations.
• Space is allocated dynamically as elements are added, so only the space
proportional to the number of elements is used.
• Free from Overflow
Task Execution Time Comparison

Task Array List Linked List

insert(i) Location Access Θ(1), Insert Task O(n) Location Access O(n), Insert Task Θ(1)

pop(i) Location Access Θ(1), Delete Task O(n) Location Access O(n), Delete Task Θ(1)

remove(x) Element Find O(n), Delete Task O(n) Element Find O(n), Delete Task Θ(1)

get(i) Θ(1) O(n)


• List
• Array List (Python Built-in List)
• Linked List
• Array List vs. Linked List
• Improvement and
Improvement and Expansion for Linked List
Expansion for
Linked List

Week 4
Fall 2024
Improvement 1: Circular Linked List
• Linking next to the first node instead of ending with null
value
• The accessibility difference between the front and the
back has been eliminated

Example of a Circular Linked List with the dummy head node


Insertion for a Circular Linked List
with a dummy head
def insert(self, i:int, newItem) -> None:
if (i >= 0 and i <= self.__numItems):
prev = self.getNode(i - 1)
newNode = ListNode(newItem, prev.next)
prev.next = newNode
if i == self.__numItems:
self.__tail = newNode
self.__numItems += 1
else:
print("index", i, ": out of bound in insert()") # 필요시 에러
Handles errors처리
as necessary

Inserting an element at the end of the Circular Linked List which has
the dummy head
Improvement 2: Variable Parameter
• Reminder: pop(i) always required the position of the
element to be deleted
• Improvement: Position no longer needed
pop(i): delete element in the
ith position
pop(): delete last element
pop(-1): delete last element
Improvement 2: Variable Parameter
def pop(self, *args):
# 가변 This 파라미터
is to process. 인자가 없거나when
the last element -1이면 there마지막 원소로 or
is no parameter, 처리하기
arguments, or if.it’s 1.
위함
Satisfies
# 파이썬 리스트 규칙 만족the Python List rule
if self.isEmpty():
return None
# 인덱스 i 결정
Determines index i
if len(args) != 0: # pop(k)
Assign과 i=k같이 인자가
if there 있으면like
is an argument i=kpop(k)
할당
i = args[0]
if len(args) == 0 or i == -1: # pop() 에i 인자가
Assign elementpop(-1)
to the last없거나 if there is이면 i에 맨 끝
no argument 인덱스
in pop() 할당
or pop(-1)
i = self.__numItems - 1
# i번 원소ith삭제
Delete . 이후는
element. 앞절의
Following codepop(i) 와 같음
is the same . preceding pop(i)
as the
if (i >= 0 and i <= self.__numItems - 1):
prev = self.getNode(i - 1)
retItem = prev.next.item
prev.next = prev.next.next
if i == self.__numItems - 1:
self.__tail = prev
self.__numItems -= 1
return retItem
else:
return None
Improvement 3: Iteration
• Representative Design Pattern
• Allows easy traversal of the elements in an object.

Examples of Tasks that traverse elements:


count(), extend(), copy()

Requirements for Python Iteration:


1. Iteration Class
2. Creation of Iteration Object
the Class must have __iter__() method
3. Returns the next element
the Iteration Class must have __next()__ method.
Improvement 3: Iteration
class CircularLinkedList:

def __iter__(self): # generating iterator and return
return CircularLinkedListIterator(self)
Iteration Object
Creation
Iteration Class
class CircularLinkedListIterator:
def __init__(self, alist):
self.__head = alist.getNode(-1) # dummy head
self.iterPosition = self.__head.next # 0Node번 노드 #0
def __next__(self):
if self.iterPosition == self.__head: # 순환 End 끝
of the Loop
raise StopIteration
Retrieves the else: # 현재 원소
Returns the리턴하면서
current element다음
then 원소로
moves to이동
the next element
next element item = self.iterPosition.item
self.iterPosition = self.iterPosition.next
return item

Usage Example
def printList(self):
for element in self:
print(element, end=' ')
print()
Complete Code: Circular Linked List
from DS.list.listNode import ListNode

class CircularLinkedList:
def __init__(self):
self.__tail = ListNode("dummy", None)
self.__tail.next = self.__tail
self.__numItems = 0

def insert(self, i:int, newItem) -> None:


if (i >= 0 and i <= self.__numItems):
prev = self.getNode(i - 1)
newNode = ListNode(newItem, prev.next)
prev.next = newNode
if i == self.__numItems:
self.__tail = newNode
self.__numItems += 1
else:
print("index", i, ": out of bound in insert()") # 필요시
Handles에러
error 처리
as necessary

def append(self, newItem) -> None:


newNode = ListNode(newItem, self.__tail.next)
self.__tail.next = newNode
self.__tail = newNode
self.__numItems += 1 1/5
def pop(self, *args):
# 가변This is to process. 인자가
파라미터 없거나when
the last element -1이면there마지막 원소로or처리하기
is no parameter, arguments,위함 . 파이썬
or if it’s 리스트
1.Satisfies 규칙List
the Python 만족
rule
if self.isEmpty():
return None
# 인덱스
Determines i 결정 index i
if len(args) != 0: # pop(k) Assign과 i=k같이 인자가
if there 있으면like
is an argument i=kpop(k)
할당
i = args[0]
if len(args) == 0 or i == -1: # pop() 에i 인자가
Assign element pop(-1)
to the last없거나 if there is이면 i에 맨 끝
no argument 인덱스
in pop() 할당
or pop(-1)
i = self.__numItems - 1
# i번 원소
Delete ith 삭제
element
if (i >= 0 and i <= self.__numItems - 1):
prev = self.getNode(i - 1)
retItem = prev.next.item
prev.next = prev.next.next
if i == self.__numItems - 1:
self.__tail = prev
self.__numItems -= 1
return retItem
else:
return None

def remove(self, x):


(prev, curr) = self.__findNode(x)
if curr != None:
prev.next = curr.next
if curr == self.__tail:
self.__tail = prev
self.__numItems -= 1
return x
else: 2/5
return None
def get(self, *args):
# 가변This is to process. 인자가
파라미터 없거나when
the last element -1이면there마지막 원소로or처리하기
is no parameter, arguments,위함 . 파이썬
or if it’s 리스트
1.Satisfies 규칙List
the Python 만족
rule
if self.isEmpty():
return None
# 인덱스 i 결정
Determines index i
if len(args) != 0: # pop(k)
Assign과 i=k같이 인자가
if there 있으면like
is an argument i=kpop(k)
할당
i = args[0]
if len(args) == 0 or i == -1: # pop() 에i to
Assign 인자가 element pop(-1)
the last없거나 if there is이면 i에 맨 끝
no argument 인덱스
in pop() 할당
or pop(-1)
i = self.__numItems - 1
# i번 원소
Returns 리턴
the ith element
if (i >= 0 and i <= self.__numItems - 1):
return self.getNode(i).item
else:
return None
def index(self, x) -> int:
cnt = 0
for element in self:
if element == x:
return cnt
cnt += 1
return -12345
def isEmpty(self) -> bool:
return self.__numItems == 0
def size(self) -> int:
return self.__numItems
def clear(self):
self.__tail = ListNode("dummy", None)
self.__tail.next = self.__tail
self.__numItems = 0 3/5
def count(self, x) -> int:
cnt = 0
for element in self:
if element == x:
cnt += 1
return cnt
def extend(self, a): # a는
a is순환가능한
all objects that모든 객체
can be traversed
for x in a:
self.append(x)
def copy(self) -> 'CircularLinkedList':
a = CircularLinkedList()
for element in self:
a.append(element)
return a
def reverse(self) -> None:
head = self.__tail.next # dummy head
prev = head; curr = prev.next; next = curr.next
curr.next = head; head.next = self.__tail; self.__tail = curr
for i in range(self.__numItems - 1):
prev = curr; curr = next; next = next.next
curr.next = prev
def sort(self) -> None:
a = []
for element in self:
a.append(element)
a.sort()
self.clear()
for element in a:
self.append(element) 4/5
def __findNode(self, x) -> (ListNode, ListNode):
head = prev = self.__tail.next # dummy head
curr = prev.next # 0번 노드
while curr != head:
if curr.item == x:
return (prev, curr)
else:
prev = curr; curr = curr.next
return (None, None)
def getNode(self, i:int) -> ListNode:
curr = self.__tail.next # dummy head, index: -1
for index in range(i+1):
curr = curr.next
return curr
def printList(self) -> None:
for element in self:
print(element, end=' ')
print()
def __iter__(self): # generating iterator and return
return CircularLinkedListIterator(self)
class CircularLinkedListIterator:
def __init__(self, alist):
self.__head = alist.getNode(-1) # dummy head
self.iterPosition = self.__head.next # 0번 노드
Node #0
def __next__(self):
if self.iterPosition == self.__head: # 순환 End 끝
of Iteration
raise StopIteration
else: # 현재 원소
Returns the 리턴하면서
current element다음 원소로
and move 이동
to the next element
item = self.iterPosition.item
self.iterPosition = self.iterPosition.next
return item 5/5
Doubly Linked List

Example of a Doubly Linked List


10 17 35 40 55

head

Initial State: Empty list

head
Node Structdure

prev item next

class BidirectNode:
def __init__(self, newItem, prevNode:'BidirectNode', nextNode:'BidirectNode'):
self.item = newItem
self.prev = prevNode
self.next = nextNode
Doubly Linked List with the dummy head
newNode ← BidirectNode(newItem, prev, prev.next)
newNode.next.prev ← newNode
Insert prev.next ← newNode
numItems++

curr.prev.next ← curr.next
Delete curr.next.prev ← curr.prev
numItems--

10 35 40 55

head  No need to classify middle or the front


 Task at the front is identical the one in the middle

Initial State: Empty list


head
Circular Doubly Link List with
the dummy head Version that contains all link
methods of the Linked List

Example of a Circular Link List with the dummy header


and sample of the empty list
Insert
newNode ← BidirectNode(newItem, prev, prev.next)
newNode.next.prev ← newNode
prev.next ← newNode
numItems++

dummy head
10 35 40 55

head prev

dummy head
10 35 40 55

38
head prev
Example of inserting an element to a Circular Linked List newNode
Confirmation: This is OKAY for inserting an element in the front.
newNode ← BidirectNode(newItem, prev, prev.next)
newNode.next.prev ← newNode
prev.next ← newNode
numItems++

dummy head dummy head


10

head head
prev prev
Delete
curr.prev.next ← curr.next
curr.next.prev ← curr.prev
numItems--

17 35 40

CurrNode
Confirmation: When deleting an element at the front, this is OKAY

curr.prev.next ← curr.next
curr.next.prev ← curr.prev
numItems--

dummy head dummy head


10 10

head currNode head curr


Complete Code: Circular Doubly Linked List
from bidirectNode import BidirectNode

class CircularDoublyLinkedList:
def __init__(self):
self.__head = BidirectNode("dummy", None)
self.__head.prev = self.__head
self.__head.next = self.__head
self.__numItems = 0

def insert(self, i:int, newItem) -> None:


if (i >= 0 and i <= self.__numItems):
prev = self.getNode(i - 1)
newNode = BidirectNode(newItem, prev, prev.next)
newNode.next.prev = newNode
prev.next = newNode
self.__numItems += 1
else:
print("index", i, ": out of bound in insert()") # 필요시
Handles에러 처리
error as necessary

def append(self, newItem) -> None:


prev = self.__head.prev
newNode = BidirectNode(newItem, prev, self.__head)
prev.next = newNode
self.__head.prev = newNode
self.__numItems += 1
… 1/5
def pop(self, *args):
# 가변This is to process. 인자가
파라미터 the last element
없거나when -1이면 there마지막
is no parameter,
원소로or처리하기 arguments,위함 or if it’s
. 파이썬1.Satisfies
리스트 the Python
규칙List
만족rule
if self.isEmpty():
return None
# 인덱스
Determines i 결정
index i
if len(args) != 0: # pop(k)
Assign과 i=k같이 인자가
if there 있으면like
is an argument i=kpop(k)
할당
i = args[0]
if len(args) == 0 or i == -1: # pop() 에 i인자가
Assign elementpop(-1)
to the last없거나 이면
if there is i에 맨 끝
no argument 인덱스
in pop() 할당
or pop(-1)
i = self.__numItems - 1
# i번the
Delete 원소 삭제
ith element
if (i >= 0 and i <= self.__numItems - 1):
prev = self.getNode(i)
retItem = curr.item
curr.prev.next = curr.next
curr.next.prev = curr.prev
self.__numItems -= 1
return retItem
else:
return None

def remove(self, x):


curr = self.__findNode(x)
if curr != None:
curr.prev.next = curr.next
curr.next.prev = curr.prev
self.__numItems -= 1
return x
else:
return None 2/5
def get(self, *args):
Same as … class CircularLinkedList …
def index(self, x) -> int:
Same as … class CircularLinkedList …

def isEmpty(self) -> bool:


Same as … class CircularLinkedList …

def size(self) -> int:


Same as … class CircularLinkedList …

def clear(self):
self.__head = BidirectNode("dummy", None, None)
self.__head.prev = self.__head
self.__head.next = self.__head 3/5
self.__numItems = 0
def count(self, x) -> int:
Same as … class CircularLinkedList …
a is순환가능한
def extend(self, a): # a는 all objects that모든
are traversable
객체
Same as … class CircularLinkedList…

def copy(self) -> 'CircularDoublyLinkedList':


a = CircularDoublyLinkedList()
Same as … class CircularLinkedList…

def reverse(self) -> None:


prev = self.__head; curr = prev.next; next = curr.next
self.__head.next = prev.prev; self.__head.prev = curr
for i in range(self.__numItems):
curr.next = prev; curr.prev = next
prev = curr; curr = next; next = next.next
def sort(self) -> None: 4/5
Same as … class CircularLinkedList…
def __findNode(self, x) ->BidirectNode:
curr = self.__head.next # 0번 노드
Node #0
while curr != self.__head:
if curr.item == x:
return curr
else:
curr = curr.next
return None
def getNode(self, i:int) -> BiDirectNode:
curr = self.__head # dummy head, index: -1
for index in range(i+1):
curr = curr.next
return curr
def printList(self) -> None:
for element in self:
print(element, end=' ')
print()
def __iter__(self): # generating iterator and return
return CircularDoublyLinkedListIterator(self)
class CircularDoublyLinkedListIterator:
def __init__(self, alist):
self.__head = alist.getNode(-1) # dummy head
self.iterPosition = self.__head.next # 0Node
번 노드 #0
def __next__(self):
if self.iterPosition == self.__head: # 순환 끝the Traversal
End of
raise StopIteration
else: # 현재 원소
Returns the리턴하면서 다음
current element and 원소로 이동
move to the next element
item = self.iterPosition.item
self.iterPosition = self.iterPosition.next
return item
5/5

You might also like