38(循环左移思想 大题)

38 date:2021.3.22
在这里插入图片描述
要点:
链表
排序算法

详细代码如下:

#include  <stdio.h>
#include  <stdlib.h>
#define    N    6
typedef struct node {
    
    
  int  data;
  struct node  *next;
} NODE;
void fun(NODE  *h)
{
    
     NODE  *p, *q;    int  t;
  p = h;
  while (p) {
    
    
/**********found**********/
	  q = p->next ; //q指向p的后一个结点
/**********found**********/
     while (q) //q是否为空来判断循环是否结束
     {
    
      if (p->data > q->data)
       {
    
      t = p->data;  p->data = q->data;  q->data = t;  }
       q = q->next;
    }
/**********found**********/
	 p = p->next ; //找到一个最小的数时p应该后移
  }
}
NODE *creatlist(int  a[])
{
    
      NODE  *h,*p,*q;        int  i;
   h=NULL;
   for(i=0; i<N; i++)
   {
    
      q=(NODE *)malloc(sizeof(NODE));
      q->data=a[i];
      q->next = NULL;
      if (h == NULL)  h = p = q;
      else    {
    
      p->next = q;  p = q;   }
   }
   return  h;
}
void outlist(NODE  *h)
{
    
      NODE  *p;
   p=h;
   if (p==NULL)  printf("The list is NULL!\n");
   else
   {
    
      printf("\nHead  ");
      do
      {
    
      printf("->%d", p->data); p=p->next;  }
      while(p!=NULL);
      printf("->End\n");
  }
}
void main()
{
    
      NODE  *head;
   int  a[N]= {
    
    0, 10, 4, 2, 8, 6 };
   head=creatlist(a);
   printf("\nThe original list:\n");
   outlist(head);
   fun(head);
   printf("\nThe list after inverting :\n");
   outlist(head);
}


在这里插入图片描述
要点:
循环左移思想

详细代码如下:

#include <stdio.h>
#define    N    80
void  fun(int  *w, int  p, int  n)
{
    
    
	/*
		analyse:

		循环左移思想
	*/

	int x,j,ch;

	for(x = 0; x<=p; x++) //0 --- p需要移动p+1次
	{
    
    
		ch = w[0];
		for(j = 1; j<n; j++)
		{
    
    
			w[j-1]=w[j]; //将p+1到n-1(包含n-1)之间的数组元素依次向前移动p+1个存储单元
		}
		w[n-1] = ch;
	}


	/* ERROR:
	int i,j = 0,k;

	//遍历要移动的前部内容
	for(i = 0; i<=p; i++)
	{
		w[j++]=w[i];
	}

	//计算长度
	for(i=p+1; w[i]!='\0'; i++);

	for(k = i-1; k <n; k++)
	{
		w[k] = w[j];
	}
	*/


}
void main()
{
    
      int  a[N]={
    
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
   int  i,p,n=15;void NONO ();
   printf("The original data:\n");
   for(i=0; i<n; i++)printf("%3d",a[i]);
   printf("\n\nEnter  p:  ");scanf("%d",&p);
   fun(a,p,n);
   printf("\nThe data after moving:\n");
   for(i=0; i<n; i++)printf("%3d",a[i]);
   printf("\n\n");
   NONO();
}

猜你喜欢

转载自blog.csdn.net/weixin_44856544/article/details/115066709
今日推荐