C++/공부 정리
진수변환, 연결리스트 준비
sondiaa
2021. 10. 14. 16:18
진수변환
16진수와 2진수의 빠른 변환
2진수를 뒤에서 부터 4자릿수 씩 잘라서 변환하기
16진수를 10진수로 바꾸는 경우, 2진수로 먼저 변환 후 변환하면 더 편하게 할 수 있다.
연결리스트 준비
new 연산자는 주소를 리턴한다. 따라서 포인터로 받아야함
ex) int *p = new int;
포인터와 new 연산자 익숙해지기
#include <iostream>
using namespace std;
struct Node
{
int x, y;
};
int main()
{
Node *p = new Node({3, 7});
Node *q = new Node({4, 2}), *r = p;
cout << (*q).y << ' ' << r->x;
return 0;
}
#include <iostream>
using namespace std;
struct Node
{
int x;
Node *p;
};
int main()
{
Node *head = new Node();
head->x = 1;
head->p = new Node();
head->p->x = 2;
head->p->p = NULL;
return 0;
}
#include <iostream>
using namespace std;
struct Node
{
int x;
Node *q;
};
int main()
{
Node *head = new Node();
head->x = 3;
head->q = new Node();
head->q->x = 7;
head->q->q = new Node();
head->q->q->x = 4;
head->q->q->q = new Node();
head->q->q->q->x = 2;
head->q->q->q->q = NULL;
return 0;
}
#include <iostream>
using namespace std;
struct Node
{
int x;
Node *q;
};
int main()
{
Node *head = new Node();
head->x = 3;
head->q = new Node();
head->q->x = 7;
head->q->q = new Node();
head->q->q->x = 4;
head->q->q->q = new Node();
head->q->q->q->x = 2;
head->q->q->q->q = NULL;
Node *p;
for(p = head; p != NULL; p = p->q)
cout << p->x << ' ';
p = head;
cout << '\n';
while(1)
{
cout << p->x << ' ';
p = p->q;
if(p == NULL)
break;
}
return 0;
}
뒤에 노드 추가해주기(addNode 함수)
#include <iostream>
using namespace std;
struct Node
{
int x;
Node *next;
};
Node *head;
Node *last;
void addNode(int num)
{
if(head == NULL)
{
head = new Node();
head->x = num;
last = head;
}
else
{
last->next = new Node();
last = last->next;
last->x = num;
}
}
int main()
{
addNode(1);
addNode(2);
return 0;
}
addNode를 사용하여 추가 후 반복문으로 탐색하기
#include <iostream>
using namespace std;
struct Node
{
int n;
Node *next;
};
Node *head, *last;
void addNode(int num)
{
if(head == NULL)
{
head = new Node();
head->n = num;
last = head;
}
else
{
last->next = new Node();
last = last->next;
last->n = num;
}
}
int main()
{
addNode(3);
addNode(7);
addNode(1);
addNode(4);
addNode(2);
addNode(6);
Node *p = head;
while(p != NULL)
{
cout << p->n;
p = p->next;
}
return 0;
}