#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// ptr代表的是整個Link List的開頭!
struct data {
int val;
char text[64];
struct data *next;
} *ptr = (struct data *)NULL;
unsigned int gun_Count = 0;
inline static void append_back(struct data **, int, char *);
inline static void delete_node(struct data *, int);
inline static void search_and_delete_node(struct data *, int);
inline static void display(struct data *);
inline static void freeLinkList(struct data *);
int main(void)
{
int nVal = -1;
char temp[64];
while (gun_Count < 5) {
printf("INPUT: \n");
printf("NO: ");
scanf("%d", &nVal);
if (nVal == 0)
break;
printf("TEXT: ");
memset(temp, '\0', sizeof(char) * 64);
scanf("%s", temp);
printf("\n");
append_back(&ptr, nVal, temp);
gun_Count++;
}
display(ptr);
printf("Which Node would you want to DELETE?? ");
nVal = 0;
scanf("%d", &nVal);
search_and_delete_node(ptr, nVal);
display(ptr);
freeLinkList(ptr);
return 0;
}
inline static void append_back(head, value, string)
struct data **head;
int value;
char *string;
{
struct data *new_node = (struct data *)NULL;
struct data *last = *head;
new_node = (struct data *)malloc(sizeof(struct data));
new_node->val = value;
strncpy(new_node->text, string, strlen(string));
new_node->next = (struct data *)NULL;
if (*head == (struct data *)NULL) {
*head = new_node;
return;
}
while (last->next != (struct data *)NULL)
last = last->next;
last->next = new_node;
return;
}
inline static void
delete_node(head, value)
struct data *head;
int value;
{
struct data *current = head;
struct data *prev = (struct data *)NULL;
// 假如傳進來的Link list不是空指標,並且要刪除的節點就是第一筆
if (current != (struct data *)NULL && current->val == value) {
// 把第2個節點的記憶體位置設定給head,變成Link list的頭!
head = current->next;
free((void *)current);
return;
}
while (current != (struct data *)NULL && current->val != value) {
prev = current;
current = current->next;
}
if (current == (struct data *)NULL)
return;
prev->next = current->next;
free((void *)current);
return;
}
inline static void
search_and_delete_node(head, value)
struct data *head;
int value;
{
struct data *current = head;
while (current != (struct data *)NULL) {
if (current->val == value) {
// printf("current->val = %d \n", current->val);
delete_node(head, value);
}
current = current->next;
}
return;
}
inline static void display(head)
struct data *head;
{
printf("\nOutput: \n");
while (head != (struct data *)NULL) {
printf("%d: %s \n", head->val, head->text);
head = head->next;
}
printf("\n");
return;
}
inline static void freeLinkList(head)
struct data *head;
{
struct data *current = (struct data *)NULL;
struct data *temp = (struct data *)NULL;
current = head;
while (current != (struct data *)NULL) {
temp = current;
current = current->next;
free((void *)temp);
}
return;
}