サムネがコーヒーの記事は書きかけです。

Pythonで線形リストの実装

最近よくJavaで線形リストを使うことがあるので、pythonでも実装してみます。

Nodeクラス

ポインタと要素の二つを保持するNodeクラスを作成します。

class Node:

コンストラクタ

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

メソッド

直接メンバ変数にアクセス可能ですが、敢えてセッターとゲッターを作っておきます。

def get_data(self):
        return self.data

    def set_data(self,data) -> None:
        self.data = data
    
    def get_next(self):
        return self.next

    def set_next(self,next) -> None:
        self.next = next

線形リストクラス

上記のNodeクラスを踏まえたうえで、線形リストを作っていきいます。

class LinkedList:

コンストラクタ

def __init__(self,data) -> None:
        self.head = Node(data)
        self.length = 0

追加メソッド

リストの最後尾にパラメータとして受け取ったデータを接続します。

def add(self,data) -> bool:
        if data == None:
            return False
        self.length += 1
        currNode = self.head
        while(currNode.get_next() != None):
            currNode = currNode.get_next()
        currNode.set_next(Node(data))
        return True

削除メソッド

パラメータとして受け取ったインデックスの要素を削除し、接続をつなぎ変えます。

def remove(self,index) -> bool:
        if index > self.length or index < 0:
            print("Index out of range.")
            return False
        currNode = self.head
        if index == 0:
            self.head = currNode.get_next()
            return True
        for i in range(index-1):
            currNode = currNode.get_next()
        temp = currNode.get_next().get_next()
        val = currNode.get_next()
        currNode.get_next().set_data(None)
        currNode.set_next(temp)
        return True

toStringメソッド

クラスをターミナルに出力できるようにします。

def __repr__(self) -> str:
        result = ""
        currNode = self.head
        while(currNode.get_next() != None):
            result +=  "|{}|-".format(currNode.get_data())
            currNode = currNode.get_next()
        result +=  "|{}|".format(currNode.get_data())
        return result

_add_()

線形リストクラス同士を接続できるようにします。

def __add__(self,other)->None:
        currNode = self.head
        while(currNode.get_next() != None):
            currNode = currNode.get_next()
        currNode.set_next(other.head)
        return self

実行結果

if __name__ == "__main__":
    l = LinkedList(1)
    l.add(2)
    l.add(3)
    l.add(4)
    l.add(5)
    print(f"l1:{l}")

    l2 = LinkedList(6)
    l2.add(7)
    l2.add(8)
    l2.add(9)
    l2.add(10)
    print(f"l2:{l2}")
    print(f"l1+l2:{l+l2}")
>>>
l1:|1|-|2|-|3|-|4|-|5|
l2:|6|-|7|-|8|-|9|-|10|
l1+l2:|1|-|2|-|3|-|4|-|5|-|6|-|7|-|8|-|9|-|10|
l2+l1:|1|-|2|-|3|-|4|-|5|-|6|-|7|-|8|-|9|-|10|

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です