단방향 연결리스트(c언어)

2022. 3. 5. 21:39·Data structure

기본main함수 설정

- 동적할당을 이용하기때문에 메모리해제가 필요

int main()
{
	node* head = (node*)malloc(sizeof(node));
	head->next = NULL;
	node* curr = head->next;
	while (curr != NULL)
	{
		printf("%d\n", curr->data);
		curr = curr->next;
	}
	curr = head->next;
	while (curr != NULL)
	{
		node* next = curr->next;
		free(curr);
		curr = next;
	}
}

 

노드를 위한 구조체

typedef struct NODE
//단일방향의 노드 구조체
{
	int data;
	struct NODE* next;
}node;

 

헤드다음의 노드를 추가하는 함수

void addNode(node* target, int data)
//헤드다음에 노드를 추가하는 함수
{
	node* newNode = (node*)malloc(sizeof(node));
	newNode->next = target->next;
	newNode->data = data;
	target->next = newNode;
}

 

헤드다음의 노드를 삭제하는 함수

void removeNode(node* target)
//헤더다음 노드를 삭제하는 함수
{
	node* remove = target->next;
	target->next = remove->next;
	free(remove);
}

 

특정위치에 노드를 삽입하는 함수

void insert(node* target, int pos, int data)
//특정위치에 노드를 삽입하는 함수
{
	node* curr = target;
	node* newNode = (node*)malloc(sizeof(node));
	newNode->data = data;
	newNode->next = NULL;
	if (pos == 0)
	{
		newNode->next = target->next;
		target->next = newNode;
	}
	else
	{
		int cnt = 0;
		while (cnt != pos)
		{
			if (cnt == (pos - 1))
			{
				newNode->next = curr->next;
				curr->next = newNode;
			}
			curr = curr->next;
			cnt++;
		}
	}
}

 

728x90
저작자표시 (새창열림)

'Data structure' 카테고리의 다른 글

연결리스트로 Stack 구현하기 - c언어  (0) 2022.03.14
양방향 연결리스트(c언어)  (0) 2022.03.06
dfs, bfs  (0) 2021.12.05
유클리드 호제법  (0) 2021.12.02
에라토스의 체(python)  (0) 2021.12.02
'Data structure' 카테고리의 다른 글
  • 연결리스트로 Stack 구현하기 - c언어
  • 양방향 연결리스트(c언어)
  • dfs, bfs
  • 유클리드 호제법
study ticket
study ticket
  • study ticket
    혼자하는 공부
    study ticket
  • 전체
    오늘
    어제
    • 개발 (77)
      • 오류 (1)
      • Spring (13)
      • Java (0)
      • Data structure (6)
      • Algorithm (49)
        • 백준 (17)
        • 프로그래머스 (2)
      • 문제풀면서 알게되는것들 끄적 (2)
      • 머신러닝 (4)
        • sklearn (3)
        • pandas (1)
      • 프로젝트 (0)
        • 핏두 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준1157
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
study ticket
단방향 연결리스트(c언어)
상단으로

티스토리툴바