-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA_CircleLinkedList_MidTerm.c
134 lines (103 loc) · 2.09 KB
/
A_CircleLinkedList_MidTerm.c
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef int element;
typedef struct ListNode {
element data;
struct ListNode* link;
}ListNode; //Singly Linked List를 위한 구조체
ListNode* insert_first(ListNode* head, element data);
ListNode* insert_last(ListNode* head, element data);
//delete first와 last구현
ListNode* delete_first(ListNode* head);
ListNode* delete_last(ListNode* head);
void print_list(ListNode* head);
int main(void)
{
ListNode* head = NULL;
printf("[insert_first사용]\n");
for (int i = 0; i < 5; i++)
{
head = insert_first(head, i);
print_list(head);
}
printf("[insert_last사용]\n");
head = insert_last(head, 10);
print_list(head);
printf("[delete_first사용]\n");
head = delete_first(head);
print_list(head);
printf("[delete_last사용]\n");
head = delete_last(head);
print_list(head);
return 0;
}
ListNode* insert_first(ListNode* head, element data)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->data = data;
if (head == NULL)
{
//head안에 아무것도 없는 경우
head = node;
node->link = head;
}
else
{
node->link = head->link;
head->link = node;
}
return head;
}
ListNode* insert_last(ListNode* head, element data)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->data = data;
if (head == NULL)
{
head = node;
node->link = head;
}
else
{
node->link = head->link;
head->link = node;
head = node;
}
return head;
}
ListNode* delete_first(ListNode* head)
{
ListNode* p = NULL;
p = head->link;
head->link = p->link;
free(p);
return head;
}
ListNode* delete_last(ListNode* head)
{
ListNode* p, * p2;
p = head->link;
while (p->link != head)
{
p = p->link;
}
p2 = head;
p->link = p2->link;
head = p;
free(p2);
return head;
}
void print_list(ListNode* head)
{
ListNode* p;
if (head == NULL)
return;
p = head->link;
while (p != head)
{
printf("%d -> ", p->data);
p = p->link;
}
printf("%d->\n", p->data); //지금의 p는 head
}