链表

来源:互联网 发布:h5滑动 js代码 编辑:程序博客网 时间:2024/04/29 07:41
#include<stdlib.h>#include<math.h>#include<stdio.h>typedef struct LNode{int data;LNode *next;}LNode,*LinkList;bool is_prime(int k){for(int i=2;i<=(int)sqrt((double)k);i++){if(k%i==0)return false;}return true;}void del_prime(LinkList &L){LNode *p=L->next,*pre=L,*q;while(p!=NULL){if(is_prime(p->data)){q=p;p=p->next;pre->next=p;free(q);}else{pre=p;p=p->next;}}}void build_tail(LinkList &L){L=(LinkList)malloc(sizeof(LNode));L->next=NULL;LNode *p=L,*q;int num;for(int i=1;i<=8;i++){scanf("%d",&num);q=(LNode*)malloc(sizeof(LNode));q->data=num;q->next=NULL;p->next=q;p=p->next;}}void build_head(LinkList &L){L=(LinkList)malloc(sizeof(LNode));L->next=NULL;LNode *q;int num;for(int i=1;i<=8;i++){scanf("%d",&num);q=(LNode*)malloc(sizeof(LNode));q->data=num;q->next=L->next;L->next=q;}}void print(LinkList L){LNode *p=L->next;while(p!=NULL){printf("%d ",p->data);p=p->next;}printf("\n");}void R_print(LNode *L){  //倒序输出,传入指针是L->next;if(L!=NULL){R_print(L->next);printf("%d ",L->data);}}void del_min(LinkList &L){  //删除链表中值最小的结点LNode *p=L->next,*pre=L,*pos=NULL;int min=0x3fffffff;while(p!=NULL){if(p->data<min){pos=pre;min=p->data;}pre=p;p=p->next;}LNode *q=pos->next;pos->next=pos->next->next;free(q);}void reverse(LinkList &L){  //头插法将链表逆置LNode *p=L->next,*pos,*pl=L->next->next;L->next->next=NULL;while(pl!=NULL){pos=pl->next;pl->next=p;p=pl;L->next=p;pl=pos;}}void sort_list(LinkList &L){  //插入排序链表LNode *p=L->next->next,*ppre=L->next,*pos,*pre,*cur;while(p!=NULL){pos=L->next;pre=L;bool flag=false;cur=NULL;while(pos!=p){if(p->data<pos->data){cur=p->next;p->next=pos;pre->next=p;ppre->next=cur;p=cur;flag=true;break;}else{pre=pos;pos=pos->next;}}if(!flag){ppre=p;p=p->next;}}}int main(){LinkList L;build_tail(L);//del_prime(L);//del_min(L);//reverse(L);//sort_list(L);//R_print(L->next);print(L);return 0;}

0 0
原创粉丝点击