c- linkedList insertion

SeHoony·2022년 4월 30일
0
#include <stdio.h>
#include <stdlib.h>

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

void push(struct Node **headRef, int newData)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->next = (*headRef); // head가 바라보고 있는 주소를 newNode의 next가 바라본다.
    (*headRef) = newNode;       // head가 newNode를 바라본다.
}

void insertAfter(struct Node *prevNode, int newData)
{
    if (prevNode == NULL)
    {
        printf("이전 노드의 값이 NULL이면 안된다.");
        return;
    }
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->next = prevNode->next;
    prevNode->next = newNode;
}

void append(struct Node **headRef, int newData)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    struct Node *last = *headRef;

    newNode->data = newData;
    newNode->next = NULL;

    // 연결리스트가 비어있을 경우, 새로 생성
    if (*headRef == NULL)
    {
        *headRef = newNode;
        return;
    }

    while (last->next != NULL)
    {
        last = last->next;
    }
    last->next = newNode;
    return;
}

void printList(struct Node *node)
{
    while (node != NULL)
    {
        printf(" %d ", node->data);
        node = node->next;
    }
}

int main(void)
{
    struct Node *head = NULL;
    // head = (struct Node *)malloc(sizeof(struct Node));

    append(&head, 6);
    push(&head, 7);
    push(&head, 1);
    append(&head, 4);
    insertAfter(head->next, 8);

    printList(head);
    return 0;
}
profile
두 발로 매일 정진하는 두발자, 강세훈입니다. 저는 '두 발'이라는 이 단어를 참 좋아합니다. 이 말이 주는 건강, 정직 그리고 성실의 느낌이 제가 주는 분위기가 되었으면 좋겠습니다.

0개의 댓글