/*在开始之前最好把基本链表的组成基本原理理解清楚*/
#define LEN sizeof(struct node)
//链表节点结构体
typedef struct node
{
int num;
struct node *next;
}Node;
Node *add_node()
{
int temp_num;
Node *pnew = NULL;
pnew = (Node *)malloc(LEN);
printf("please input num:");
scanf("%d",&temp_num);
while(getchar() != '\n');
pnew -> num = temp_num;
pnew ->next = NULL;
return pnew;
}
bool yes_or_no(const char *str)
{
char sel;
while(1)
{
printf("%s",str);
scanf("%c",&sel);
switch(sel)
{
case 'y':
case 'Y':
return true;
case 'n':
case 'N':
return false;
default:
printf("input ERROR!\n");
}
}
}
Node *creat_list(Node *head) //创建链表
{
Node *pnew;
while(1)
{
pnew = add_node();
pnew ->next = head;
head = pnew;
if(yes_or_no("continue y/n?") == false)
{
break;
}
}
return head;
}
void print_list(Nod/e *head) //显示链表
{
Node *p = head;
if(head != NULL)
{
while(p != NULL)
{
printf("[num: %d,addr:%p]\n",p->num,p->next);
p = p ->next;
}
}
}
void modify_node(Node *head)//修改
{
int temp_num;
printf("please input the num that you wanna modify: ");
scanf("%d",&temp_num);
while(getchar() != '\n');
while(h/ead != NULL)
{
if(head -> num == temp_num)
{
printf("please input the num which is modified:");
scanf("%d",temp_num);
while(getchar() != '\n');
head -> num = temp_num;
return ;
}
head = head -> next;
}
printf("Not found!\n");return;
}
int list_len(Node *head)//链表长度
{
int len = 0;
while(head != NULL)
{
len++;
head = head -> next;
}
return head;
}
Node *find_pre(Node *head,Node *delete)
{
while(head != NULL)
{
if(head ->next == delete)
{
return head;
}
head = head -> next;
}
}
Node *delete_node(Node *head,Node *delete)
{
if(head == delete)
{
head = head -> next;
}
else
{
Node *pre =find_pre(head,delete);
pre -> next = delete -> next;
}
return head;
}
Node *find_node(Node *head)
{
int temp_num;
printf("please input the num that you wanna delete:");
scanf("%d",&temp_num);
while(getchar() != '\n');
while(head != NULL)
{
if(head -> num == temp_num)
{
return head;
}
head = head -> next;
}
return NULL;
}
Node *delete_list(Node *head)//删除节点
{
Node *delete = find_node(head);
if(delete ==NULL)
{
printf("Not found!\n");
return head;
}
head = delete_node(head,delete);
free(delete);
return head;
}
int main(int argc, char *argv[])
{
Node *head = NULL;
head = creat_list(head);
print_list(head);
printf("\n");
modify_node(head);
print_list(head);
delete_list(head);
print_list(head);
printf("list_len = %d\n",list_len(head));
return 0;
}
链表的增、删、改、查、显示(C 语言实现)
最新推荐文章于 2022-07-20 00:44:40 发布