辣子呀

单向链表

#include<stdio.h>
#include<stdlib.h>
#define N 6

typedef struct node{
int data;
struct node *next;
}ElemSN;

ElemSN * Creatlink(int a[]);
int Count(ElemSN *h);
int Countoddnode(ElemSN *h);
ElemSN *Maxnode(ElemSN *h);
void Print(ElemSN *h);
ElemSN * PPrintlink(ElemSN *h);
void Printlink(ElemSN *h1);

int main(void)
{
int a[6]={3,2,5,8,4,7};
ElemSN *head,*pmax,*h1;
int n,m;
//创建单向链表
head=Creatlink(a);
//输出结点个数
n=Count(head);
printf("结点个数%d\n",n);
//奇数结点个数
m=Countoddnode(head);
printf("奇数结点个数%d\n",m);
//返回最大值
pmax=Maxnode(head);
printf("最大值%d\n",pmax->data );
//输出单向链表
Print(head);
printf("\n");
//逆向输出单向链表
h1=PPrintlink(head);
Printlink(h1);
}

ElemSN * Creatlink(int a[])
{
int i;
ElemSN *h,*p;
h=p=(ElemSN *)malloc(sizeof(ElemSN));
h->data=a[0];
h->next=NULL;
for(i=1;i<N;i++)
{
p=p->next =(ElemSN *)malloc(sizeof(ElemSN));
p->data=a[i];
p->next=NULL;
}
return h;
}

int Count(ElemSN *h)
{
ElemSN *p;
int n=0;
for(p=h;p!=NULL;p=p->next)
{
n++;
}
return n;
}

int Countoddnode(ElemSN *h)
{
ElemSN *p;
int count=0;
for(p=h;p;p=p->next)
{
if(p->data %2)
count++;
}
return count;
}

ElemSN *Maxnode(ElemSN *h)
{
ElemSN *p,*pm;
for(pm=h,p=h->next ;p;p=p->next)
{
if(p->data >pm->data )
pm=p;
}
return pm;
}

void Print(ElemSN *h)
{
ElemSN *p;
for(p=h;p!=NULL;p=p->next)
{
printf("%5d",p->data);
}
}

ElemSN * PPrintlink(ElemSN *h)
{
ElemSN *p,*h1=NULL; //头插法
while(h)
{
p=h;
h=h->next;
p->next=h1;
h1=p;
}
return h1;
}
void Printlink(ElemSN *h1)
{
ElemSN *p;
for(p=h1;p!=NULL;p=p->next)
{
printf("%5d",p->data);
}
}

posted on 2018-09-24 18:33  辣子呀  阅读(104)  评论(0编辑  收藏  举报

导航