SLL 기본 개념

우리누리·2022년 8월 8일
0

SLL은 Single Linked List의 약자이며
데이터들을 저장하기위해 사용되는 데이터 구조이다.
DLL과 다르게 데이터들이 한쪽 방향 (단방향)으로만 연결 되어있는 것을 말한다.

이는 Node를 이용하여 데이터와 다음 방향의 노드를 가리킬 Next 포인터를 주로 이용한다.

코드

#define max_node 10000


struct node {
	int data;
	node* next;
};

node node[max_node];
int nodecnt=0;
node* head;

node* getnode(int data) {
	node[nodecnt].data = data;
	node[nodecnt].next = nullptr;
	return &node[nodecnt++];
}

void init()
{
	if (head != 0)
	{
		head->next = nullptr;
	}
	
}

void addnode2head(int data)
{
	node* node=getnode(data);
	node->next = head;
	head = node;

}

void addnode2tail(int data)
{
	node* node = getnode(data);
	node* temp = head;
	while (temp->next != 0)
	{
		temp = temp->next;
	}
	temp->next = node;
}

void addnode2num(int data, int num)
{
	node* node = getnode(data);
	node* temp_prev = head;
	node* temp = head;
	if (num == 1)
	{
		node->next = head;
		head = node;
		return;
	}
	else
	{
		temp = head;
		for (int i = 0; i < num-1; i++)
		{
			temp = temp->next;
			if (i > 0)
			{
				temp_prev = temp_prev->next;
			}
		}
		if (temp_prev->next != 0)
		{
			node->next = temp_prev->next;
		}
		temp_prev->next = node;
	}
}

void removenode(int data)
{
	node* temp = head;
	if (head->data == data)
	{
		head = head->next;
		return;
	}
	while (temp->next != 0 && temp->next->data != data)
	{
		temp = temp->next;
	}
	if (temp->next != 0)
	{
		temp->next = temp->next->next;
	}
}

int getlist(int output[max_node])
{
	int cnt = 0;
	node* temp = head;
	if (head != 0)
	{
		while (1)
		{
			output[cnt] = temp->data;
			if (temp->next == 0)
			{
				break;
			}
			temp = temp->next;
			cnt++;
		}
	}
	return cnt + 1;
}

설명

getnode 함수는 새로운 data값을 갖는 노드를 생성하는 것.

init 함수는 새로운 테스크 케이스마다 head를 초기화 해주는 것.

addnoed2tail은 Linked List의 맨 끝 부분에 새로운 노드를 추가해주는 것.

addnode2num은 Linked List에서 원하는 순서(num)에 해당하는 data값을 추가해주는 것.

removenide는 해당하는 data값을 갖고 있는 node를 지우는 것.

getlist는 현재 갖고 있는 총 node의 개수를 반환하는 것.

0개의 댓글