본문 바로가기

자료구조

(C++ 자료구조) 선형 자료구조 - Linked List

728x90

Array :

- A data structure consisting of a collection of values


- Each identified by array index  -  L[0], L[3] 처럼 indexing 가능


- array를 선언하게 되면, 메모리의 연속적인 공간을 할당받게 된다.


- creation of an array (정적 할당, 동적 할당)   

ex) Type* d = new Type[size]   /   delete [] d

Type[size] 크기만큼의 메모리를 new! 만들어서 해당 메모리 주소를 d에 할당한다!

Array in Memory :

- 배열을 선언을 하게 되면, 연속적인 메모리를 할당받게 된다. 


Pointer (*)

- a variable storing a memory address 

 

Reference Operator  (&)

- Returns the address of a variable

 

Dereference Operator  (*)

- Returns the value at the pointer address

 

Function Call with Pointers

-Two types of passing arguments to a function:


1. Call by value : passing values
2. Call by reference : passing addresses

 


Insertion and Deletion in Arrays -> Linked Lists (새로운 자료구조)

 

Linked Lists

 

- A linear collection of data elements


- Order is not given by their physical placement in memory  -  리스트처럼 index가 있지 않다!, 메모리가 연속적으로 할당되지 않는다.


- Each element points to the next


- Each node consists of an item and a link


- 데이터 수를 정확히 예측할 수 없거나, 데이터의 갯수가 계속해서 바뀌는 경우에 Linked Lists를 이용하면 좋다.

 

Linked List Implementation

 

- A node consists of an item and a next pointer


- A linked list has its length and a pointer to the head node


Arrow and Box Representation

 

- Box : an item
- Arrow : a  pointer to the next box
- The head points the first node.

 

#include <iostream>
#include <list> // STL 의 LinekdList 호출

int main(void) {
	std::list<int>L = { 3,7 };
	// LinkedList의 iterator 활용
	std::list<int>::iterator cur = L.begin();

	L.push_front(1);
	for (auto i : L)
		std::cout << i << ' ';
	std::cout << '\n';

	L.push_back(10);
	for (int i : L)
		std::cout << i << ' ';
	std::cout << '\n';

	L.insert(cur, 5);
	for (int i : L)
		std::cout << i << ' ';
	std::cout << '\n';

	L.pop_front();
	for (int i : L)
		std::cout << i << ' ';
	std::cout << '\n';

	L.pop_back();
	for (int i : L)
		std::cout << i << ' ';
	std::cout << '\n';

	cur++;
	L.erase(cur);

	for (int i : L)
		std::cout << i << ' ';
	std::cout << '\n';
}


// 그럼 cur 의 값 또느 cur이 가리키는 위치의 값은 어떻게 아는가??

//1 3 7
//1 3 7 10
//1 5 3 7 10
//5 3 7 10
//5 3 7
//5 3