-
-
Save jangsoopark/7739305 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct A { | |
int num; | |
struct A* next; | |
}; | |
//global variable | |
struct A *ptr = NULL; // for list tour | |
struct A *head = NULL; // point list head(first) | |
struct A *tail = NULL; // point list tail(end) | |
int Insert(int num); | |
void Delete_all(void); | |
int Delete(int num); | |
void Print(void); | |
int main(void) | |
{ | |
/* | |
main 함수는 알아서 해서 내면 되 | |
*/ | |
Delete_all(); | |
return 0; | |
} | |
int Insert(int num) | |
{ | |
struct A* new = (struct A*)malloc(sizeof(struct A));//memory allocation | |
struct A* pre = NULL; | |
//memory allocation failed | |
if (new == NULL) return 0; | |
// set node value | |
new->num = num; | |
new->next = NULL; | |
// the first Insert | |
if(head == NULL) | |
{ | |
head = new; | |
tail = new; | |
} | |
else | |
{ | |
ptr = head; | |
//search proper location | |
while(ptr && (ptr->num < num)) | |
{ | |
pre = ptr; | |
ptr = ptr->next; | |
} | |
//Insert | |
if(ptr == head) | |
{ | |
new->next = head; | |
head = new; | |
} | |
else if(ptr == NULL) | |
{ | |
tail->next = new; | |
tail = new; | |
} | |
else | |
{ | |
new->next = ptr; | |
pre->next = new; | |
} | |
} | |
return 1; | |
} | |
void Delete_all(void) | |
{ | |
ptr = head; | |
while(head) | |
{ | |
ptr = head; | |
head = head->next; | |
free(ptr); | |
} | |
} | |
int Delete(int num) | |
{ | |
struct A* pre = NULL; | |
ptr = head; | |
// search | |
while(ptr && (ptr->num != num)) | |
{ | |
pre = ptr; | |
ptr = ptr->next; | |
} | |
//delete | |
if(ptr == head) | |
{ | |
head = head->next; | |
} | |
else if(ptr == tail) | |
{ | |
tail = pre; | |
pre->next = NULL; | |
} | |
else if(ptr == NULL) | |
{// node is noneexistent | |
return 0; | |
} | |
else | |
{ | |
pre->next = ptr->next; | |
} | |
free(ptr); | |
return 1; | |
} | |
void Print(void) | |
{ | |
ptr = head; | |
while(ptr) | |
{ | |
printf("%d -> ", ptr->num); | |
ptr = ptr->next; | |
} | |
printf("NULL\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment