链表创建,头插法,尾插法。

链表创建,头插法,尾插法。,第1张

#include
#include
#include

typedef  int  ElemType;

struct  node
{
ElemType  data;          //数据成员data类型为ElemType类型
struct node  * next;
} ;
typedef  struct node  LNode; 
typedef  struct node * LinkList; 
void input(ElemType *s);
void output(ElemType s);
int compare(ElemType a,ElemType b);
void CreateTailList (LinkList L);//用头插法创建一个单链表L
void OutputList (LinkList  L);//输出以L为头的单链表各结点的值
LNode * searchmax(LinkList L);
void DestroyList (LinkList  L);
int  main()
{
LNode * max;

LinkList  head;       //head是保存单链表的表头结点地址的指针
if( ( head =(LNode *) malloc( sizeof(LNode) ) )==NULL) 
{  printf("申请空间失败!"); 
exit(0); 

head->next=NULL; 
CreateTailList(head);
printf("创建的单链表:\n");
OutputList(head);
max=searchmax(head);
printf("最大值:\n");
output(max->data );
printf("\n");
DestroyList (head);
}

//用尾插法创建带头结点的单链表
void CreateTailList(LinkList  L) 
{
ElemType flag=-1,x;
LNode *p,* tail;
int i=0;
tail=L;              //设置尾指针,方便插入
input(&x);      //x为char型变量;
while ( compare(x,flag)!=0)

   p=(LNode *)malloc(sizeof(LNode)); 
            if(p==NULL) 
    { 
      printf("申请空间失败!"); 
                exit(0); 

            p->data=x;           //x的实际数据类型为struct stu
   p->next=NULL; 
    tail->next=p; 
tail=p; 
input(&x);

void OutputList (LinkList  head)//输出以head为头的链表各结点的值
{
struct node *p;
p=head->next ;//取得链表的头指针
while(p!=NULL)//只要是非空表
{
output(p->data);    //调用output(p->data)输出结点的数据
p=p->next;                       //p指向下一个结点
}
printf("\n");
}
void  DestroyList (LinkList  head)//输出以head为头的链表各结点的值
{
struct node *p,*q;
p=head;           //取得链表的头指针
while(p!=NULL)    //只要是非空表
{
q=p->next;
free(p);
p=q;
}
}
void input(ElemType *s)
{
scanf("%d",&(*s));   
}
void output(ElemType s)
{
printf("%d\t",s);
}

int compare(ElemType  a, ElemType b)
{
if (a==b)
     return 0;
else
    if (a      return -1;
else
     return 1;
}

LNode * searchmax (LinkList  list)
{
LinkList  p = list->next;//上一个节点的指针
LNode *  max ;//当前节点
max=p ;
while(p)
{
if(compare(p->data ,max->data)>0)
{
max=p ;
}
p  = p->next;
}
return max;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/584768.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存