#动态链表
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
typedef struct node Node;
void add (Node **head , int data)//增加结点
{
Node *p = *head;
Node * newnode = (Node *)malloc(sizeof(Node));
newnode ->data = data;
newnode ->next = NULL;
if (*head == NULL)
{
*head = newnode;
}
else{
while (p->next != NULL)
p = p->next;
p->next = newnode;
}
}
void printlist (Node *head)//打印链表
{
Node *p;
for (p = head ; p != NULL ; p = p ->next)
printf("%d ",p->data);
}
int countlist (Node *head)
{
Node *p;
int sum = 0;
for (p = head ; p != NULL ; p = p->next) sum ++;
return sum;
}
void fun (Node **head)//清空链表
{
Node *p = *head;
Node *fre = *head;
while (p != NULL)
{
fre = p;
p = p->next;
free(fre);
}
*head = NULL;
}
void deletelist (Node **head , int x)//删除数据域为x的结点
{
Node *p = *head;
Node *t = *head;
while (p -> next != NULL)
{
if (p -> next -> data == x)
{
t = p->next;
p ->next = t ->next;
free(t);
}
else p = p ->next;
}
p = *head;
if (p ->data == x)
{
*head = p ->next;
free(p);
}
}
int main()
{
Node *head = NULL;//生存空链表
for (int i = 0 ; i < 9 ; i ++)
{
add (&head , i);
}
printf("%d\n",countlist(head));
printlist(head);
//puts("");
//fun(&head);
//printf("%d\n",countlist(head));
deletelist(&head , 2);
puts("");
printlist(head);
return 0;
}