본문 바로가기
코테 문제

[아무문제] 정해진 그룹으로 역출력하는 프로그램

by 케찹이 2020. 4. 24.

순서대로인 배열이 있으면 몇묶음씩을 거꾸로 출력하는 프로그램이다.

6

1 2 3 4 5 6

2

로 입력값을 집어 넣게 되면 출력값은

1->2->3->4->5->6->NULL

3->2->1->6->5->4->NULL

같이 나온다. 

 

#include<stdio.h>
#include<stdlib.h>

typedef struct _Node{
	int data;
	struct _Node* next;
}Node;

void printList(Node* head){
	Node* ptr = head;
	while(ptr){
		printf("%d",ptr->data);
		printf("->");
		ptr = ptr->next;
	}
	printf("NULL");
	printf("\n");
}

void push(Node** head, int data){
	Node* newNode = (Node*)malloc(sizeof(Node));
	newNode->data = data;
	newNode->next = *head;
	*head = newNode;
}

Node* Reserve(Node* head, int g){
	int arr[100];
	Node* tempt=NULL;
	int max;
	
	int i=0;
	while(head){
		arr[i] = head->data;
		head = head->next;
		max = arr[i];
		i++;
	}
	
	if(max % g == 0){
		int part = max/g;
		
		for(int l=1;l<=part;l++){
			for(int j=0;j<g;j++){
				push(&tempt,arr[g*(part-l)+j]);
			}
		}
		
	}
	else{
		int partx = max/g;
		int remain = max%g;
		
		for(int m = 0;m<remain;m++){
			push(&tempt,arr[g*partx+m]);
		}
		
		for(int l=1;l<=partx;l++){
			for(int j=0;j<g;j++){
				push(&tempt,arr[g*(partx-l)+j]);
			}
		}
		
	}
	return tempt;
	
}

int main(){
	int N, list[100],g;
	scanf("%d",&N);
	
	for(int i =0;i<N;i++)
		scanf("%d",&list[i]);
		
	Node* head = NULL;
	
	scanf("%d",&g);
	
	for(int i = N-1;i>=0;i--)
		push(&head,list[i]);
		
	printList(head);
	head = Reserve(head,g);
	printList(head);
	
	return 0;
}

댓글