#define _CRT_SECURE_NO_WARNINGS
#include
#include
struct node {
char data;
struct node* next;
};
typedef struct node NODE;
/* This function creates a linked list with N nodes. */
NODE* create_link_list(int n)
{
int i;
NODE* head, * p, * q;
if (n == 0) return NULL;
head = (NODE*)malloc(sizeof(NODE));
p = head;
printf("Please input %d chars for the linked list:\n", n);
for (i = 0; i < n; i++)
{
scanf(" %c", &(p->data));
q = (NODE*)malloc(sizeof(NODE));
p->next = q;
p = q;
}
p->next = NULL; // 将最后一个节点的next指针设置为NULL
return (head);
}
/* This function inserts a node whose value is b before the node whose value is a, if the node is not exist,
then insert it at the end of the list. */
void insert(NODE** p_head, char a, char b)
{
NODE* p, * q;
q = (NODE*)malloc(sizeof(NODE));
q->data = b;
q->next = NULL;
if (*p_head == NULL) *p_head = q;
else
{
p = *p_head;
while (p->data != a && p->next != NULL)
p = p->next;
if (p->next == NULL)
p->next = q;
else
{
q->next = p->next;
p->next = q;
}
}
}
/* The function deletes the node whose value is a, if success, return 0, or return 1. */
int deletenode(NODE** p_head, char a)
{
NODE* p, * q;
p = NULL;
q = *p_head;
if (q == NULL) return(1);
if (q->data == a)
{
*p_head = q->next;
free(q);
return (0);
}
else
{
while (q->data != a && q->next != NULL)
{
p = q;
q = q->next;
}
if (q->data == a)
{
p->next = q->next;
free(q);
return(0);
}
else
return(1);
}
}
int main()
{
NODE* my_head, * p;
int m;
char ch_a, ch_b;
/* create a linked list with m nodes */
printf("Please input the number of nodes for the linked list:\n");
scanf("%d", &m);
my_head = create_link_list(m);
/* output the linked list */
printf("The linked list is like:\n");
p = my_head;
while (p != NULL)
{
printf("%c ", p->data);
p = p->next;
}
printf("\n");
/* insert a node whose value is b before a */
printf("Please input the position for a:\n");
scanf(" %c", &ch_a);
printf("Please input the value that you want to insert:\n");
scanf(" %c", &ch_b);
insert(&my_head, ch_a, ch_b);
printf("The linked list after insertion is like:\n");
p = my_head;
while (p != NULL)
{
printf("%c ", p->data);
p = p->next;
}
printf("\n");
/* delete a node whose value is a */
printf("Please input the position for a:\n");
scanf(" %c", &ch_a);
if (deletenode(&my_head, ch_a) == 0)
{
printf("The linked list after deleting is like:\n");
p = my_head;
while (p != NULL)
{
printf("%c ", p->data);
p = p->next;
}
printf("\n");
}
else
printf("Failed to delete.\n");
return 0;
}