0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++で連結リストを実装してみた

Last updated at Posted at 2023-03-10

実装イメージは以下の通り。

絵日記2023.png

ソースファイルは以下の通り。

list2.cpp
#include <iostream>

class List {
public:
  int data;
  List *pointer;
};

List *list;
List *list_;
List *list_header;

void push(int data){
  list_ = new List[1];
  list_->data = data;
  list_->pointer = (List *)NULL;
  List *list_next = list_header;
  while(list_next->pointer != (List *)NULL){
    list_next = list_next->pointer;
  }
  list_next->pointer = list_;
}

void show(){
  List *list_next = list_header;
  while(list_next != (List *)NULL){
    std::cout << list_next->data << std::endl;
    list_next = list_next->pointer;
  }
}

int main(){

  list_header = new List[1];
  list_header->data = 0;
  list_header->pointer = (List *)NULL;
  list = new List[1];
  list->data = 0;
  list->pointer = (List *)NULL;
  list_header->pointer = list;
  
  std::cout << "---" << std::endl;
  push(100);
  show();
  std::cout << "---" << std::endl;
  push(200);
  show();
  std::cout << "---" << std::endl;
  push(300);
  show();
}

コマンドラインの実行結果は以下の通り。

$ g++ list2.cpp
$ ./a.out 
---
0
0
100
---
0
0
100
200
---
0
0
100
200
300
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?