C언어 연결리스트 구현

John Jeong (토론 | 기여)님의 2017년 8월 16일 (수) 00:51 판 (새 문서: ==개요== ;C언어 링크드 리스트, 연결 리스트 ;C Language Linked LIst * C언어에서 링크드 리스트 구현 <source lang='C'> #include <stdio.h> #include <stdlib.h>...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

C언어 링크드 리스트, 연결 리스트
C Language Linked LIst
  • C언어에서 링크드 리스트 구현
#include <stdio.h>
#include <stdlib.h>

typedef struct nodeTag {
	int v;
	struct nodeTag *next;
} nodeType;

nodeType* createNode(int v)
{
	nodeType *p;

	p = malloc(sizeof(nodeType));
	p->v = v;
	p->next = NULL;

	return p;
}

void destroyNode(nodeType **node)
{
	free(*node);

	*node = NULL;
}

void appendNode(nodeType **head, nodeType *newNode)
{
	nodeType *ptr = *head;

	if(ptr == NULL) {
		*head = newNode;
	}
	else {
		while(ptr->next != NULL) {
			ptr = ptr->next;
		}
		ptr->next = newNode;
	}
}

void insertAfter(nodeType *ptr, nodeType *newNode)
{
	newNode->next = ptr->next;
	ptr->next = newNode;
}

nodeType *getNode(nodeType *head, int index)
{
	nodeType *ptr = head;

	while(ptr->next != NULL && index > 0) {
		index--;
		ptr = ptr->next;
	}

	return ptr;
}

void printList(nodeType *head)
{
	nodeType *ptr = head;

	while(ptr != NULL) {
		printf("%d\n", ptr->v);
		ptr = ptr->next;
	}
}

int main()
{
	nodeType *head = NULL;
	nodeType *ptr;

	appendNode(&head, createNode(1));
	appendNode(&head, createNode(2));
	appendNode(&head, createNode(3));
	appendNode(&head, createNode(4));

	printList(head);

	ptr = getNode(head, 0);
	insertAfter(ptr, createNode(5));

	printList(head);

	return 0;
}

2 같이 보기

[[분류: C언어]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}