码迷,mamicode.com
首页 > 移动开发 > 详细

链表结点的移动(最大值移到尾结点)

时间:2018-08-03 11:32:26      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:web   define   bottom   idt   break   null   pac   循环   指针   

#include<stdio.h>

#include<stdlib.h>

#define N 9

typedef struct node{

   int  data;

   struct node * next;

}ElemSN;

ElemSN  * Createlink(int a[]){            //逆向创建单向链表

    int i;

    ElemSN * h=NULL, * p;

    for( i=N-1;i>=0;i--){

          p=(ElemSN *)malloc(sizeof(ElemSN));

          p->data =a[i];

          p->next=h;

          h=p;

    }

    return h;

   }

   void Printlink(ElemSN * h){

       ElemSN * p;

       for(p=h;p;p=p->next)

   printf("%2d\n",p->data);

   }

   ElemSN * MoveMaxnodeToTail(ElemSN*h){

         ElemSN * Pmax,* p,* Qmax,* q;

Pmax=h;

         for(q=h,p=h->next;p;q=p,p=p->next){

  if(Pmax->data<p->data){

        Pmax=p;

        Qmax=q;

  }

  }                                      //for循环出来p等于null,q为尾结点,Pmax最大值结点,Qmax最大值结点的上一结点

if(Pmax->next) {             //判断最大值结点是否为尾结点

if(Pmax!=h)            //判断最大值结点是否为头结点

    Qmax->next=Pmax->next; //断链挂链

else

            h=h->next;   //是头结点,头结点指针h后移

Pmax->next=q->next; //关键操作:如果不把最大值结点的next给NULL(q->next等于NULL),次链就位单向循环链表

q->next=Pmax;//最大值挂到尾结点

        }

return h;

   }

   int main(void){

int a[]={9,3,5,8,4,7,2,6,1};

         ElemSN * head;

head=Createlink(a,9);

head=MoveMaxnodeToTail(head);

Printlink(head);

   }


链表结点的移动(最大值移到尾结点)

标签:web   define   bottom   idt   break   null   pac   循环   指针   

原文地址:http://blog.51cto.com/13645380/2153945

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!