#include <stdio.h> #include <malloc.h> #define NULL 0 typedef struct node { int data; struct node *next; }ElemSN; ElemSN * creat_link(int ms); //逆向创建一个链表 void print_link(ElemSN *head); //输出单向链表 ElemSN * delete_node(ElemSN *head, int x); //删除链表中的一个结点 int count_link(ElemSN *head); //统计单向链表结点的个数 ElemSN * clear_link(ElemSN *head); //删除链表 int main() { ElemSN *head; int ms, x; printf("Please input node number:"); scanf("%d", &ms); head = creat_link(ms); print_link(head); printf("Please input delete node:"); scanf("%d", &x); head = delete_node(head, x); print_link(head); printf("link member is :%d\n", count_link(head)); head = clear_link(head); } ElemSN * creat_link(int ms) { ElemSN *h = NULL, *p; int i, x; for(i = 0; i < ms; i++) { printf("Please input data:"); scanf("%d", &x); p = (ElemSN *)malloc(sizeof(ElemSN)); p->data = x; p->next = h; h = p; } return h; } void print_link(ElemSN *head) { for(; head; head = head->next) { printf("%d ", head->data); } printf("\n"); } ElemSN * delete_node(ElemSN *head, int x) { ElemSN *p = NULL, *q = NULL; if(NULL == head) { return NULL; } for(p = head; p && p->data != x; q = p, p = p->next); //p && p->data != x不能交换位置 if(NULL == p) //没有找到要删除的结点 { return head; } if(NULL == q) //要删除的是头结点 { head = head->next; } else { q->next = p->next; } free(p); return head; } int count_link(ElemSN *head) { int count = 0; for(; head; count++, head = head->next); return count; } ElemSN * clear_link(ElemSN *head) { ElemSN *p; while(head) { p = head->next; free(head); head = p; } return head; }
链表(二)——单向链表的基本操作(创建、删除、打印、结点个数统计),布布扣,bubuko.com
链表(二)——单向链表的基本操作(创建、删除、打印、结点个数统计)
原文地址:http://blog.csdn.net/laoniu_c/article/details/37884735