본문 바로가기
알고리즘

연결 리스트

by pagehit 2020. 6. 20.
반응형

연결 리스트(linked list)

파이썬

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None

    
    def print_list(self):
        temp = self.head
        while temp:
            print(temp.data, end=" ")
            temp = temp.next


if __name__ == "__main__":
    linkedlist = LinkedList()
    linkedlist.head = Node(1)
    second = Node(2)
    third = Node(3)

    linkedlist.head.next = second
    second.next = third

    linkedlist.print_list()

 

자바

public class LinkedList {
    Node head;

    class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
            next = null;
        }
    }

    public void printList() {
        Node n = head;
        while (n != null) {
            System.out.print(n.data + " ");
            n = n.next;
        }
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.head = list.new Node(1);
        list.head.next = list.new Node(2);
        list.head.next.next = list.new Node(3);

        list.printList();
    }    
}

 

C++

#include <iostream>

class Node {
public:
    int data;
    Node* next;
};

class LinkedList {
public:
    Node* head;
};

void print_list(LinkedList* l) {
    Node* n = l->head;
    while (n != NULL) {
        std::cout << n->data << " ";
        n = n->next;
    }
    std::cout << std::endl;
}

int main() {
    LinkedList* first = new LinkedList();
    Node* second = new Node();
    second->data = 1;
    
    first->head = second;

    second->next = new Node();
    second->next->data = 2;

    print_list(first);

    return 0;
}

 

결과

1 2 3 

 

반응형

댓글