早教吧 育儿知识 作业答案 考试题库 百科 知识分享

数据结构的题目第一题答案已经给出来了想要知道具体过程!1.假设以数组S[0..m-1]作为循环队列的存储结构,同时设变量front和rear分别指向队头元素的前一个位置和队尾元素位置,则队列中元素

题目详情
数据结构的题目
第一题答案已经给出来了 想要知道具体过程!
1.假设以数组S[0..m-1]作为循环队列的存储结构,同时设变量front和rear分别指向队头元素的前一个位置和队尾元素位置,则队列中元素个数为 (rear-front+m)%m .
2.指出下述程序段的功能是什么?
(1) void Demo1(SeqStack *S){
    int i; arr[64] ; n=0 ;
    while ( StackEmpty(S)) arr[n++]=Pop(S);
    for (i=0,i< n; i++) Push(S,arr[i]);
   } //Demo1
(2) SeqStack S1,S2,tmp;
  DataType x;
  ...//假设栈tmp和S2已做过初始化
  while ( StackEmpty (&S1))
   {
    x=Pop(&S1) ;
    Push(&tmp,x);
   }
  while ( StackEmpty (&tmp) )
   {
    x=Pop( &tmp);
    Push( &S1,x);
    Push( &S2,x);
   }
(3) void Demo2( SeqStack *S,int m)
   { // 设DataType 为int 型
    SeqStack T; int i;
    InitStack (&T);
    while StackEmpty( S))
     if(( i=Pop(S)) =m) Push( &T,i);
    while StackEmpty( &T))
     {
      i=Pop(&T); Push(S,i);
     }
   }
(4)void Demo3( CirQueue *Q)
   { // 设DataType 为int 型
    int x; SeqStack S;
    InitStack( &S);
    while QueueEmpty( Q ))
     {x=DeQueue( Q); Push( &S,x);}
    while StackEmpty( &s))
     { x=Pop(&S); EnQueue( Q,x );}
   }// Demo3
(5) CirQueue Q1,Q2; // 设DataType 为int 型
  int x,i ,n= 0;
  ...// 设Q1已有内容,Q2已初始化过
  while ( QueueEmpty( &Q1) )
   { x=DeQueue( &Q1 ) ; EnQueue(&Q2,x); n++;}
  for (i=0; i< n; i++)
   { x=DeQueue(&Q2) ;
  EnQueue( &Q1,x) ; EnQueue( &Q2,x);}
▼优质解答
答案和解析
1.假设以数组S[0..m-1]作为循环队列的存储结构,同时设变量front和rear分别指向队头元素的前一个位置和队尾元素位置,则队列中元素个数为 (rear-front+m)%m .
对于普通队列,如果变量front和rear分别指向队头元素的前一个位置和队尾元素位置,则队列中元素个数为 rear-front .
考虑到这里是循环队列,所以队列中元素个数为 (rear-front+m)%m.
2.指出下述程序段的功能是什么?
(1) void Demo1(SeqStack *S){
    int i; arr[64] ; n=0 ;
    while ( StackEmpty(S)) arr[n++]=Pop(S);
    for (i=0,i< n; i++) Push(S,arr[i]);
   } //Demo1
把栈S里的元素逆序.
(2) SeqStack S1,S2,tmp;
  DataType x;
  ...//假设栈tmp和S2已做过初始化
  while ( !StackEmpty (&S1))
   {
    x=Pop(&S1) ;
    Push(&tmp,x);
   }
  while ( !StackEmpty (&tmp) )
   {
    x=Pop( &tmp);
    Push( &S1,x);
    Push( &S2,x);
   }
把栈S1中的元素按序(注意不是逆序)添加到栈S2中
(3) void Demo2( SeqStack *S,int m)
   { // 设DataType 为int 型
    SeqStack T; int i;
    InitStack (&T);
    while (!StackEmpty( S))
     if(( i=Pop(S)) !=m) Push( &T,i);
    while (!StackEmpty( &T))
     {
      i=Pop(&T); Push(S,i);
     }
   }
删除栈S中值为m的元素
(4)void Demo3( CirQueue *Q)
   { // 设DataType 为int 型
    int x; SeqStack S;
    InitStack( &S);
    while (!QueueEmpty( Q ))
     {x=DeQueue( Q); Push( &S,x);}
    while (!StackEmpty( &s))
     { x=Pop(&S); EnQueue( Q,x );}
   }// Demo3
把Q的元素逆序.
(5) CirQueue Q1,Q2; // 设DataType 为int 型
  int x,i ,n= 0;
  ...// 设Q1已有内容,Q2已初始化过
  while ( !QueueEmpty( &Q1) )
   { x=DeQueue( &Q1 ) ; EnQueue(&Q2,x); n++;}
  for (i=0; i< n; i++)
   { x=DeQueue(&Q2) ;
  EnQueue( &Q1,x) ; EnQueue( &Q2,x);}
把Q1的元素按序复制到Q2中