Notice
Recent Posts
Recent Comments
Creative Code
main.c(리스트 createNode) 본문
※main.c파일
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main(void)
{
List list;
initList(&list);
insertFirstNode(&list,4); //[4]
printList(&list);
insertFirstNode(&list,3); //[3,4]
printList(&list);
insertFirstNode(&list,1); //[1,3,4]
printList(&list);
insertNode(&list, 1, 2); //[1,2,3,4]
printList(&list);
deleteNode(&list,3); //[1,2,4]
printList(&list);
cleanupList(&list);
return 0;
}
※list.h파일
#ifndef LIST_H
#define LIST_H
typedef struct node {
int data;
struct node *next;
}Node;
typedef struct list {
Node *ptr;
}List;
void initList(List *pList);
void cleanupList(List *pList);
void printList(const List *pList);
void insertFirstNode(List *pList, int data); // 첫번째 노드에 데이터 추가
void insertNode(List *pList,int prevData, int data); // prevdata 뒤의 노드에 데이터 추가
void deleteNode(List *pList, int data); // 데이터 삭제
#endif
※list.c파일
#include "list.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
static Node* createNode(int data, Node *next) // static 전역 함수는 같은 .c파일에서만 쓸 수 있다.
{
Node *p = malloc(sizeof(Node));
assert(p);
p->data = data;
p->next = next;
return p;
}
void initList(List *pList)
{
pList ->ptr = createNode(-1,NULL); // 더미노드에는 아무값이 들어와도 상관x
}
void cleanupList(List *pList)
{
Node *ptr = pList ->ptr;
while (ptr){
Node *tmp = ptr;
ptr = ptr->next;
free(tmp);
}
}
void printList(const List *pList)
{
Node *ptr = pList->ptr->next;
printf("[");
while (ptr) {
printf("%d",ptr->data);
printf((ptr->next)? ", ":"");
ptr = ptr->next;
}
printf("]\n");
}
void insertFirstNode(List *pList, int data)
{
pList ->ptr ->next = createNode(data,pList->ptr->next);
}
void insertNode(List *pList, int prevData, int data)
{
Node *ptr = pList->ptr->next;
while (ptr){
if (ptr->data == prevData) {
break;
}
ptr = ptr->next;
}
if (ptr){
ptr ->next = createNode(data,ptr->next);
}
}
void deleteNode(List *pList, int data)
{
Node *ptr = pList->ptr->next;
Node *ptr2 = pList->ptr; // ptr뒤에서 따라가는 node
while (ptr){
if (ptr->data == data){
break;
}
ptr = ptr->next;
ptr2 = ptr2 ->next;
}
if (ptr){
ptr2->next = ptr->next;
free(ptr);
}
}
'C Programming' 카테고리의 다른 글
square(inline,매크로함수) (0) | 2023.09.11 |
---|---|
main.c(generic list) (0) | 2023.08.28 |
main.c(리스트) (0) | 2023.08.28 |
main.c(queue memcpy) (0) | 2023.08.25 |
main.c(queue malloc) (0) | 2023.08.25 |