🥚

GoとJavaを同じように使う(例:単方向連結リスト作成)

2023/03/29に公開約2,800字

javaの例

class Node { //独自型クラス ノードの定義
  int value; //値をメモ(状態を保持) インスタンス変数 obj必要
  Node next; //連結リスト 次をメモ(状態を保持) インスタンス変数

  public Node(int value) { //コンストラクタ obj必要
      this.value = value;
      this.next = null; //次は空に初期化
  }
}

class LinkedList { //独自型クラス
  Node head; //変数の宣言だけ インスタンス変数
  
  // リストを出力するメソッド
  public void printList() { //インスタンスメソッド Obj必要
      while (head != null) {
          System.out.print(head.value + " ");
          head = head.next;
      }
  }

  //挿入メソッド
  public void insertAt(int data, int position) {  //インスタンスメソッド Obj必要
      Node newNode = new Node(data);
      if (head == null) {
          head = newNode;
      } else if (position == 0) {
          newNode.next = head;
          head = newNode;
      } else {
          Node currentNode = head;
          int currentPosition = 0;
          while (currentPosition < position - 1 && currentNode.next != null) {
              currentNode = currentNode.next;
              currentPosition++;
          }
          newNode.next = currentNode.next;
          currentNode.next = newNode;
      }
  }
}

class LinkedList {
  public static void main(String[] args){ //クラスメソッド obj不要    
    LinkedList lList = new LinkedList(); //LinkedListのオブジェクト作成
    lList.head = new Node(1); //インスタンス変数に代入(Nodeのオブジェクト作成)
    var n2 = new Node(2);
    var n3 = new Node(10);
    var n4 = new Node(11);
    // ノード同士をつなぐ
    lList.head.next = n2;
    n2.next = n3;
    n3.next = n4;

    lList.insertAt(30, 2);

    lList.printList();
  }
}

goの例

package main

import (
	"fmt"
)

type Node struct { //構造体の独自型Node定義
	value int   //値をメモ(状態を保持) インスタンス変数ライク obj必要
	next  *Node //連結リスト 次をメモ(状態を保持) インスタンス変数ライク
	// 構造に参照型があるので参照渡し
}

func NewNode(size int) *Node { //コンストラクタ関数 obj必要
	return &Node{value: size}
}

type LinkedList struct { //構造体の独自型Node定義
	head *Node //変数の宣言だけ インスタンス変数ライク obj必要
	// 構造に参照型があるので参照渡し
}

func (s *LinkedList) PrintList() { //独自型ポインタの専用メソッド  obj必要
	for curr := s.head; curr != nil; curr = curr.next { 
		fmt.Printf("%d ", curr.value)
	}
}

// 挿入メソッド
func (s *LinkedList) InsertAt(data, position int) { //インスタンスメソッド Obj必要
	newNode := NewNode(data)
	if s.head == nil {
		s.head = newNode
	} else if position == 0 {
		newNode.next = s.head
		s.head = newNode
	} else {
		currentNode := s.head
		currentPosition := 0
		for currentPosition < position-1 && currentNode.next != nil {
			currentNode = currentNode.next
			currentPosition++
		}
		newNode.next = currentNode.next
		currentNode.next = newNode
	}
}

func main() {
	lList := LinkedList{}   //LinkedListインスタンス作成
	lList.head = NewNode(1) //インスタンス変数に代入(Nodeのオブジェクト作成)
	node2 := NewNode(2)
	node3 := NewNode(10)
	node4 := NewNode(11)
	// ノード同士をつなぐ
	lList.head.next = node2
	node2.next = node3
	node3.next = node4

	lList.InsertAt(30, 2)

	lList.PrintList()
}

Discussion

ログインするとコメントできます