将顺序表的元素就地逆置。空间复杂度要求O(1)。
函数接口定义:
方法接口:
public void reverse( )
裁判测试程序样例:
import java.util.Scanner;
class SqList
{
int [] listElem;
int curLen;
public SqList( ) // 创建n个元素构造的顺序表
{
Scanner sc = new Scanner(System.in);
this.listElem = new int[100];
int n = sc.nextInt();
for(int i = 0 ; i<n ;i++ )
{
this.listElem[i] = sc.nextInt();
}
this.curLen = n;
}
//输出所有元素
public void display()
{
int i;
for( i = 0 ; i <this.curLen ; i++)
{
System.out.print( this.listElem[i]+" ");
}
}
@@@
/* 请在这里填写答案 */
}
public class Main{
public static void main(String args[]){
SqList L = new SqList( );
L.reverse();
L.display();
}
}
输入样例:
输入n+1个整数 ,第1个表示 线性表长度,接下来的n个数表示 线性表的元素。
5 1 2 3 4 5
结尾无空行
输出样例:
5 4 3 2 1 在这里插入代码片
结尾无空行public void reverse( )
{
int t=0;
int j=curLen-1;
for(int i=0;i<curLen/2;i++){
if(i==j)
break;
else{
t=listElem[i];
listElem[i]=listElem[j];
listElem[j]=t;
}
j–;
}
}
该博客介绍了如何在O(1)空间复杂度下实现顺序表的元素就地逆置。通过提供一个名为`reverse`的方法,实现了数组元素的交换,从而达到逆置效果。在给定的测试程序中,顺序表的元素被输入并调用`reverse`方法进行逆置,最后输出逆置后的顺序表元素。
783

被折叠的 条评论
为什么被折叠?



