検索ガイド -Search Guide-

単語と単語を空白で区切ることで AND 検索になります。
例: python デコレータ ('python' と 'デコレータ' 両方を含む記事を検索します)
単語の前に '-' を付けることで NOT 検索になります。
例: python -デコレータ ('python' は含むが 'デコレータ' は含まない記事を検索します)
" (ダブルクオート) で語句を囲むことで 完全一致検索になります。
例: "python data" 実装 ('python data' と '実装' 両方を含む記事を検索します。'python data 実装' の検索とは異なります。)
img_for_tre_tron
Tré Thộn を食べたことがありますか?
ベトナム・ビンズオン滞在中の方は是非注文して食べてみて!
絶対に美味しいです!
ホーチミン市内へも配達可能です。お問い合わせください。

Have you ever had "Tré Thộn" before?
If you're living at Bình Dương in Vietnam, you "must" try to order and eat it.
I'm sure you're very surprised how delicious it is!!
If you're in Hồ Chí Minh, you have a chance to get it too. Please call!!
>>

【 Python Data Structures and Algorithms 】Linked List 実装 Programming Interview 解答例 投稿一覧へ戻る

Published 2020年8月1日12:44 by mootaro23

SUPPORT UKRAINE

- Your indifference to the act of cruelty can thrive rogue nations like Russia -

Linked List 実装問題の解答例です。問題は こちら から。是非挑戦してみてください。


ただ1つの正解、は存在しません。


実装方法の1つとして参考にしてください。


class Node:
"""
Linked List を構成する要素 ( ノード )。
"""

def __init__(self, name: str, age: int):
"""
:attribute next_node: 自分の次に位置するノード ( Node 型 )。自分が最後の場合は None 。
"""

self.name = name
self.age = age
self.next_node = None

def __repr__(self):
return f"{self.name}({self.age})"


class LinkedList:
"""
Linked List 実装クラス
"""

def __init__(self, first_node: Node = None):
"""
:param first_node: Linked List の最初のノード ( Node 型 )。
"""

self._first_node = first_node

def __repr__(self):
nodes = []
node = self._first_node
while node is not None:
nodes.append(repr(node))
node = node.next_node

nodes.append('None')
return ' -> '.join(nodes)

def __len__(self):
"""
:return: int型
"""

ct = 0
if (cur := self._first_node) is not None:
while cur is not None:
cur = cur.next_node
ct += 1
return ct

def prepend(self, other: Node):
"""
リストの先頭にノードを追加する。

:param other: 追加するノード
"""

if self._first_node is not None:
other.next_node = self._first_node
self._first_node = other

def append(self, other: Node):
"""
リストの最後にノードを追加する。

:param other: 追加するノード
"""

if self._first_node is None:
self._first_node = other
else:
cur = self._first_node
while cur.next_node is not None:
cur = cur.next_node
cur.next_node = other

def append_after(self, arg_name: str, other: Node):
"""
name 属性値として arg_name を持つノードの後に other を追加する。
arg_name を持つノードが存在しない場合はメッセージを表示し終了する(追加しない)。
同じ属性値を持つノードがリストに複数含まれている場合は、先頭から検索し最初にマッチしたノードの次に追加する。

:param arg_name: この値の name 属性を持つノードの後に追加する
:param other: 追加するノード
"""

cur = self.find_node(arg_name)
if cur is None:
print(f"リスト内に名前は存在しません: {arg_name}")
return

cur.next_node, other.next_node = other, cur.next_node

def find_node(self, arg_name: str):
"""
name 属性値として arg_name を持つノードを検索する。
同じ属性値を持つノードがリストに複数含まれている場合は、先頭から検索し最初にマッチしたノードを返す。

:param arg_name: この値の name 属性を持つノードを検索する
:return: 該当するノード、もしくは、None (見つからなかった場合)
"""

node = self._first_node
while node is not None and node.name != arg_name:
node = node.next_node

return node

def remove(self, arg_name: str):
"""
name 属性値として arg_name を持つノードを削除する。
同じ属性値を持つノードがリストに複数含まれている場合は、先頭から検索し最初にマッチしたノードを削除する。

:param arg_name: この値の name 属性を持つノードを削除する
"""

if self._first_node is None:
print("リストは空です")
return

cur = self._first_node
prev = None

while cur and cur.name != arg_name:
prev = cur
cur = cur.next_node

if prev is None:
# ノードの先頭、かつ、名前がマッチ
self._first_node = cur.next_node
elif cur:
# 2番目以降のノード、かつ、名前がマッチ
prev.next_node = cur.next_node
cur.next_node = None
else:
print(f"リスト内に名前は存在しません ({arg_name})。0 個のノードが削除されました。")

def reverse(self):
"""
Linked list の並び順を逆にする。
"""

if self._first_node is None:
print("リストは空です")
return

cur = self._first_node
prev = None
while cur:
following = cur.next_node
cur.next_node = prev
prev = cur
cur = following
self._first_node = prev

def reverse_recursive(self):
"""
reverse 関数の再帰バージョン
"""

def recursion(cur, prev):
if not cur:
return prev

following = cur.next_node
cur.next_node = prev

prev = cur
cur = following

return recursion(cur, prev)

self._first_node = recursion(cur=self._first_node, prev=None)


linked_list = LinkedList()


print(linked_list)
# None


print(linked_list.find_node('one'))
# None


linked_list.remove('nothing')
# リストは空です


linked_list.append(Node('two', 2))
linked_list.append(Node('three', 3))


print(linked_list)
# two(2) -> three(3) -> None


linked_list.prepend(Node('one', 1))


print(linked_list)
# one(1) -> two(2) -> three(3) -> None


linked_list.append(Node('four', 4))
linked_list.append(Node('five', 5))
linked_list.append(Node('seven', 7))


print(linked_list)
# one(1) -> two(2) -> three(3) -> four(4) -> five(5) -> seven(7) -> None


linked_list.append_after('five', Node('six', 6))


print(linked_list)
# one(1) -> two(2) -> three(3) -> four(4) -> five(5) -> six(6) -> seven(7) -> None


linked_list.reverse()


print(linked_list)
# seven(7) -> six(6) -> five(5) -> four(4) -> three(3) -> two(2) -> one(1) -> None


linked_list.reverse_recursive()


print(linked_list)
# one(1) -> two(2) -> three(3) -> four(4) -> five(5) -> six(6) -> seven(7) -> None


linked_list.remove('nothing')
# リスト内に名前は存在しません (nothing)。0 個のノードが削除されました。


linked_list.remove('one')


print(linked_list)
# two(2) -> three(3) -> four(4) -> five(5) -> six(6) -> seven(7) -> None


linked_list.remove('four')


print(linked_list)
# two(2) -> three(3) -> five(5) -> six(6) -> seven(7) -> None


linked_list.remove('seven')


print(linked_list)
# two(2) -> three(3) -> five(5) -> six(6) -> None


print(len(linked_list))
# 4


print(linked_list.find_node('three'))
# three(3)


print(linked_list.find_node('ten'))
# None
この記事に興味のある方は次の記事にも関心を持っているようです...
- People who read this article may also be interested in following articles ... -
【 Python Data Structures and Algorithms 】Python とデータ構造 ( data structure ) - linked list を実装してみよう! Linked List 実装 Python Programming Interview 模擬問題
【 Python coding challenge 】Gutenberg Project からダウンロードする実際の古典を題材に、登場人物インデックスを作成しよう! Python Programming Interview の準備にもなります【解答例】
【Python 雑談・雑学 + coding challenge】Python data structure の1つ、set を活用していますか? 複数のシーケンスの包含関係を調べるには最適です
【 Python coding challenge 】Gutenberg Project からダウンロードする実際の古典を題材に、登場人物インデックスを作成しよう! Python Programming Interview の準備にもなります
【 Effective Python, 2nd Edition 】threading モジュールの Lock クラスを利用してマルチスレッド実行時のデータ競合 ( data races ) を予防しよう! GIL はデータ構造 ( data structure ) の安全性まで面倒を見てくれません
Python coding challenge [解説編]: Basics of Graph Theory - グラフ理論の基礎総復習 - Python interview でも取り上げられます
Python coding challenge - リスト内の 0 を他の要素の順番は変えずに最後尾へ移動しよう! - two-pointer technique の利用