알고리즘

[알고리즘 C++] Linked List & Vector

gmwoo 2021. 12. 17. 11:51

 

1. Linked List를 이용해서 실행시 파라미터 숫자(argc, argv) 만큼 랜덤하게 0 ~100 사이의 숫자 생성후 최소, 최대, 평균 값 찾기 

2. vector를 이용해서 같은 문제 풀기

 

#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>

using namespace std;

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

int main(int argc, char *argv[]){
	Node *head = NULL;
	Node *tail = NULL;
	Node *cur = NULL;
	Node *newNode = NULL;

	int count = atoi(argv[1]);
	int randomNum = 0;
	
	cout << "Input Node Count : " << count << endl;

	srand((unsigned int)time(NULL));

	for(int i=0; i<count; i++){
		randomNum = rand() % 101;
		newNode = new Node();
		newNode->data = randomNum;
		newNode->next = NULL;
		if(head == NULL)
			head = newNode;
		else
			tail->next = newNode;
		tail = newNode;
	}

	int node_sum = 0;
	int node_max = 0;
	int node_min = head->data;

	cout << "Output Node : " << endl;
	
	if(head == NULL){
		return 0;
	}
	else{
		cur = head;
		cout << cur->data << " ";
		node_sum += cur->data;

		while(cur->next != NULL){
			cur = cur->next;
			cout << cur->data << " ";
			node_sum += cur->data;

			if(node_max < cur->data)
				node_max = cur->data;

			if(node_min > cur->data)
				node_min = cur->data;
		}
	}
	

	cout << "\nTotal : " << node_sum << "\n";
	cout << "Mean : " << node_sum / count << "\n";
	cout << "Min : " << node_min << "\n";
	cout << "Max : " << node_max << "\n";

	return 0;
}

 

Vector를 이용하여 풀기

#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]){
	
	int count = atoi(argv[1]);
	int node_sum = 0;

	vector<int> v;
	
	cout << "Input Node Count : " << count << endl;
	cout << "Output Node : " << endl;

	srand((unsigned int)time(NULL));
	
	for(int i=0; i<count; i++){
		v.push_back(rand() % 101);
		node_sum += v[i];
		cout << v[i] << " ";
	}

	cout << "\nTotal : " << node_sum << "\n";
	cout << "Mean : " << node_sum / count << "\n";
	cout << "Max : " << *max_element(v.begin(), v.end()) << "\n";
	cout << "Min : " << *min_element(v.begin(), v.end()) << "\n";

	return 0;
}

훨씬 간단하게 풀 수 있습니다.

반응형