单链表

来源:互联网 发布:淘宝卡西欧专卖店 编辑:程序博客网 时间:2024/05/22 17:47
 
#include<iostream>using namespace std;typedef struct stu{int age;struct stu *next;}LNode;struct stu* CreateList(int n){LNode *head,*p,*s;int num=0;head =(LNode*)malloc(sizeof(LNode));head->next=NULL;p=head;for(int i=0;i<n;i++){s=(LNode*)malloc(sizeof(LNode));printf("the age of student is");scanf("%d",&s->age);p->next = s;p=s;num++;}p->next = NULL;return head;}struct stu* delList(LNode *head,int age){LNode *r,*p;p=head;p=head->next;while(p->age != age && p!=NULL){r = p;p = p->next;}if(p->age == age){r->next=p->next;free(p);}else if(p ==NULL){printf("Don't find the node");}return head;}struct stu* insert(LNode *head,int age){LNode *s,*r;s=head->next;while(age > s->age && s->next!=NULL){r=s;s=s->next;}if(age <= s->age && s->next!= NULL){LNode *t;t=(LNode*)malloc(sizeof(LNode));t->age = age;r->next =t;t->next =s;}else if(s->next == NULL){LNode *t;t=(LNode*)malloc(sizeof(LNode));t->age = age;s->next=t;t->next = NULL;}return head;}struct stu* reverse(LNode *head){LNode *p,*q,*r;p=head;p=p->next;q=p->next;p->next = NULL;while(q != NULL){r = q->next;q->next = p;p = q;q = r;}head =(LNode*)malloc(sizeof(LNode));head->next =p;return head;}void display(LNode*p){   LNode *s;   s=p;   s=s->next;   while(s != NULL)   {   printf("the age are %d\n",s->age);   s=s->next;   }}void main(){int n=2;LNode *p;p=(LNode*)malloc(sizeof(LNode));    p=CreateList(3);display(p);cout<<endl;p=insert(p,58);p=reverse(p);display(p);}
   上面是将头指针视为不包含任何数据的情况下的,单链表的创建,插入,逆置,删除时候的代码;
	
				
		
原创粉丝点击