C언어 연결리스트 2

(C언어 연결 리스트 구현 2에서 넘어옴)

1 개요[ | ]

C언어 연결 리스트 구현 2
#include <stdio.h>
#include <stdlib.h>

// 노드 정의
typedef struct NodeStruct {
	int value;
	struct NodeStruct *next;
} Node;
// 리스트 포인터 (리스트의 시작점, 전역변수)
Node* head = NULL;

// 노드 생성 (메모리 할당)
Node* createNode(int value) {
	Node* p = malloc(sizeof(Node));
	p->value = value;
	p->next = NULL;
	return p;
}

// 노드 소멸 (메모리 해제)
void destroyNode(Node* node) {
	free(node);
	node = NULL;
}

// 리스트 맨 뒤에 노드 추가 
void append(Node* node) {
    if( head == NULL ) {
        head = node;
        return;
    }
    Node* p = head;
    while( p->next != NULL ) p = p->next;
    p->next = node;
}

// 리스트의 지정한 위치에 노드 추가
void insertAt(int index, Node* newNode) {
	if( index == 0 ) {
	    newNode->next = head;
	    head = newNode;
	    return;
	}
	Node* p = head;
	for(int i=0; i<index-1; i++) p = p->next;
    newNode->next = p->next;
	p->next = newNode;
}

// 리스트에서 지정한 위치의 노드 삭제
void deleteAt(int index) {
	if( index == 0 ) {
	    Node* u = head;
	    head = head->next;
	    destroyNode(u);
	    return;
	}
	Node* p = head;
	for(int i=0; i<index-1; i++) p = p->next;
	Node* u = p->next;
    p->next = p->next->next;
    destroyNode(u);
}

// 리스트의 모든 노드 출력
void printList() {
    Node* p = head;
	while(p != NULL) {
		printf("%d ", p->value);
		p = p->next;
	}
	printf("\n");
}

// 메인 함수
int main() {
    append(createNode(1));
    append(createNode(2));
    append(createNode(3));
    append(createNode(4));
    printList();
    // 1 2 3 4 

    insertAt(0, createNode(8));
    printList();
    // 8 1 2 3 4 
    insertAt(3, createNode(9));
    printList();
    // 8 1 2 9 3 4 
    
    deleteAt(0);
    printList();
    // 1 2 9 3 4 
    deleteAt(2);
    printList();
    // 1 2 3 4
}

2 같이 보기[ | ]

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