#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); //输出单向链表 void delete_rdy(ElemSN *head); //删除冗余的项 ElemSN * insert_node(ElemSN *head, int x); //插入结点到有序链表 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); delete_rdy(head); print_link(head); head = insert_node(head, 5); print_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"); } void delete_rdy(ElemSN *head) { ElemSN *p, *q; if(NULL == head) return; p = head; q = p->next; while(q) { if(p->data == q->data) { p->next = q->next; free(q); q = p->next; } else { p = q; q = p->next; } } } ElemSN * insert_node(ElemSN *head, int x) { ElemSN *p, *q; if(NULL == head || NULL == head->next) return NULL; p = head; q = head; //这里不能赋值为head->next,比较必须从第一个结点开始 if(q->data >= q->next->data) //递减链表 { for(; q && q->data >= x; p = q, q = q->next){} } else //递增链表 { for(; q && q->data <= x; p = q, q = q->next){} } if(NULL == q) //插入在链表尾部 { q = (ElemSN *)malloc(sizeof(ElemSN)); q->data = x; q->next = NULL; p->next = q; } else if(q == head) //插入在表首 { q = (ElemSN *)malloc(sizeof(ElemSN)); q->data = x; q->next = head; head = q; } else //插入在中间位置 { p->next = (ElemSN *)malloc(sizeof(ElemSN)); p->next->next = q; p->next->data = x; } return head; } ElemSN * clear_link(ElemSN *head) { ElemSN *p; while(head) { p = head->next; free(head); head = p; } return head; }
原文地址:http://blog.csdn.net/laoniu_c/article/details/37963819