0
1

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 3 years have passed since last update.

C言語でリスト逆順プログラム

Last updated at Posted at 2022-04-27

※追記:2022/4/27
構造体の名前はnodeにするのが一般的であるというご指摘を頂きました。
nodeに修正して、プログラムを多少改良したので追記します。

C言語でリスト逆順プログラムを作りました。
以下、コードです。

リスト逆順プログラム
#include <stdio.h>
#include <stdlib.h>

struct node{
	int data;
	struct node* next;
};

typedef struct node Node;

Node* create_node();
Node* list_reverse(Node*,Node*);
void print_list(Node*);
int scan_data();

int main(){
	
	Node* list = NULL;
	Node* next_node;
	Node* tmp_node = NULL;
	int input;
	
	list = create_node();
	list->data = -1;
	list->next = NULL;
	next_node = list;
	
	while( ( input = scan_data() ) != -1 ) {
		next_node->data = input;
		next_node->next = create_node();
		tmp_node = next_node;
		next_node = next_node->next;
	}
	
	if( tmp_node != NULL ) tmp_node->next = NULL;
	if( list->data == -1 ) list = NULL;
	
	print_list(list);
	
	list = list_reverse(list, NULL);
	
	print_list(list);
	
	return 0;
}

Node* create_node() {
	return calloc(1,sizeof(Node));
}

Node* list_reverse( Node* now_node , Node* pre_node ) {
	
	Node* tmp_node;
	
	if( now_node != NULL ) {
		tmp_node = list_reverse(now_node->next,now_node);
		now_node->next = pre_node;
		return tmp_node;
	}else{
		return pre_node;
	}
}

void print_list(Node* now_node) {
	
	while( now_node != NULL ) {
		printf("%d ",now_node->data);
		now_node = now_node->next;
	}
	printf("\n");
	
}

int scan_data() {
	int input;
	scanf("%d",&input);
	return input;
}

コマンドラインで整数を入力していって、入力し終わったら-1を入力してください。
リストのデータを順番に表示して、逆順にしたリストを表示します。

リスト逆順並び替え.png

0
1
9

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?