<pre name="code" class="cpp">#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
Node *next;
};
typedef struct Node Node;
struct List{
Node head;
Node *last;
};
typedef struct List list;
void list_init(List *list)
{
list->head.data=0;
list->head.next=0;
list->last=&list->head;/*链表尾部的指针*last指向链表的头结点head*/
}
void list_insert(List *list,int data)
{
Node *new_node=(Node *)malloc(sizeof(Node));
new_node->data=data;
new_node->next=NULL;
list->last->next=new_node;/*链接新节点*/
list->last=new_node;/*移动尾指针*/
}
void list_erase(List *list,int data)
{/*删除数据等于data的结点*/
Node *pre=&list->head;
Node *cur=list->head.next;
while(cur)
{
if(cur->data==data)
{
Node *del=cur;
pre->next=cur->next;
cur=cur->next;
free(del);
}
else
{
pre=cur;
cur=cur->next;
}
}
list->last=pre;
}
Node *list_find(List *list,int data)
{
Node *cur=list->head.next;
while(cur)
{
if(cur->data==data)
return cur;
cur=cur->next;
}
return NULL;/*如果找不到,返回NULL*/
}
void list_print(List *list)
{
printf("head");
Node *cur=list->head.next;
while(cur)
{
printf("->[%d]",cur->data);
cur=cur->next;
}
printf("\n");
}
void list_destroy(List *list)
{
Node *cur=list->head.next;
while(cur)
{
Node *del=cur;
cur=cur->next;/*先存下cur的下一个结点地址,然后再释放*/
free(del);
}
list_init(list);/*释放完后要初始化*/
}
/*for testing*/
int main()
{
List *list;
list_init(list);
list_insert(list,10);
list_insert(list,2);
list_insert(list,1);
list_insert(list,3);
list_print(list);
list_erase(list,10);
list_print(list);
list_insert(list,-99);
list_print(list);
Node *node=list_find(list,3);
printf("node next data=%d\n",node->next->data);
list_destroy(list);
return 0;
}
运行结果:
<img src="https://img-blog.csdn.net/20141109234235276?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaHljX18=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />