#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct test{
int dat;
struct test *next;
}node;
void create_node(node **list)
{
node *p,*s,*head;
int d,cycle=1;
head = (node *)malloc(sizeof(node));
head->next = NULL;
p = head;
printf("Please input your link_list data:\n");
while(cycle) {
scanf("%d",&d);
if(d!=0) {
s = (node *)malloc(sizeof(node));
s->dat = d;
p->next = s;
p = s;
}
else cycle = 0;
}
head = head->next;
p->next = NULL;
*list = head; //不用再return head的操作,这里直接可以保存head 的地址,后续操作直接可以对list操作
}
int list_len(node **head)
{
int n = 0;
node *p;
p = *head;
while(p!=NULL) {
p = p->next;
n++;
}
return n;
}
void print_list(node **head)
{
node *p;
p = *head;
if(p!=NULL) {
while(p!=NULL) {
printf("%d ",p->dat);
p = p->next;
}
}
}
void list_del(node **head,int data)
{
node *p,*p_bak;
p = *head;
while((p->dat!=data)&&(p->next!=NULL)) {
p_bak = p;
p = p->next;
}
if(p->dat==data) {
if(p==*head) {
*head = p->next;
free(p);
}
else {
p_bak->next = p->next;
}
}
else printf("No such node \n");
}
int main(void)
{
node *t;
int len;
create_node(&t);
len = list_len(&t);
printf("len=%d\n",len);
printf("The created list:\t");
print_list(&t);
printf("\nChecking the link list for data '2'\n");
list_del(&t,2);
printf("After check:\n");
print_list(&t);
return 0;
}
运行结果:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。