카테고리 없음
다양한 데이터 구조 공통 작업 2탄 삽입
by 아구몬선생
2022. 6. 28.
정렬
#include <iostream>
using namespace std;
void printArray(int arr[], int N)
{
for (int i = 0; i < N; i++) {
cout << arr[i] << ' ';
}
}
int main()
{
int arr[4];
int N = 4;
for (int i = 1; i < 5; i++) {
arr[i - 1] = i;
}
printArray(arr, N);
return 0;
}
스택
#include <bits/stdc++.h>
using namespace std;
void printStack(stack<int>& St)
{
while (!St.empty()) {
cout << St.top() << ' ';
St.pop();
}
}
int main()
{
stack<int> St;
St.push(4);
St.push(3);
St.push(2);
St.push(1);
printStack(St);
return 0;
}
큐(대기줄)
#include <bits/stdc++.h>
using namespace std;
void printQueue(queue<int>& Q)
{
while (!Q.empty()) {
cout << Q.front() << ' ';
Q.pop();
}
}
int main()
{
queue<int> Q;
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
printQueue(Q);
return 0;
}
링크드리스트
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
Node* insertEnd(Node* head, int data)
{
if (head == NULL)
return newNode(data);
else
head->next = insertEnd(head->next, data);
return head;
}
void traverse(Node* head)
{
if (head == NULL)
return;
cout << head->data << " ";
traverse(head->next);
}
int main()
{
Node* head = NULL;
head = insertEnd(head, 1);
head = insertEnd(head, 2);
head = insertEnd(head, 3);
head = insertEnd(head, 4);
traverse(head);
}