Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 자바
- 프로그래머스
- 이웃한 칸
- frontend
- 모의 주식
- 코딩테스트
- 풀스택프레임워크
- 빅데이터
- 개발자
- 코딩독학
- 코스닥
- backend
- 개발
- 프로그램
- Python
- Reflex
- 개인프로젝트
- C++
- 백준
- 사물인터넷
- 주가예측
- SNS
- java
- java정리
- 코테
- Project
- 프로그래밍
- 코딩
- 자바정리
- 자바독학
Archives
- Today
- Total
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 |