您的位置:首页 > 理论基础 > 数据结构算法

数据结构(java语言描述)栈(队列)习题

2016-03-21 22:01 891 查看

1.编写一个函数,要求借助一个栈把数组中的数据元素逆置

  代码实现(顺序栈实现)
package exercise;
import stack.sqstack;
import java.util.Scanner;
public class nizhi {
public int[] shunizhi(int[] x)throws Exception{
if(x!=null){
sqstack sq=new sqstack(x.length);
for(int i=0;i<x.length;i++){
sq.push(x[i]);
}
while(!sq.isEmpty()){
for(int i=0;i<x.length;i++){
x[i]=(int)sq.pop();
}
}
return x;
}else
return null;
}
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
System.out.println("请输入数组的大小:");
int n=sc.nextInt();
int[] ar=new int
;
System.out.println("请输入数组的元素:");
for(int i=0;i<n;i++){
ar[i]=sc.nextInt();
}
System.out.print("逆置之前的数组为: ");
for(int i=0;i<n;i++){
System.out.print(ar[i]+" ");
}
nizhi a=new nizhi();
a.shunizhi(ar);
System.out.print(" 逆置操作之后的数组为");
for(int i=0;i<n;i++){
System.out.print(ar[i]+" ");
}
}
}  

结果:

请输入数组的大小:
5
请输入数组的元素:
23
56
47
55
78
逆置之前的数组为: 23 56 47 55 78 逆置操作之后的数组为78 55 47 56 23

2.编写一个函数判断一个字符序列是否为一个回文序列。

所谓的回文序列就是正读和反读都是相同的字符序列,例如:abba和abdba均为回文序列。要求只使用栈来实现。

代码:(链栈实现)

package exercise;
import stack.Linkstack;
import java.util.Scanner;
public class Ishuiwen {
public boolean ishui(String x) throws Exception
{
Linkstack sq=new Linkstack();
int index=0;
int l=0;
while(index<x.length()){
sq.push(x.charAt(index));
//System.out.println(sq.peek());
index++;
}
for(int i=0;i<x.length();i++){
if(sq.peek()!=null){
String t=sq.pop().toString();
//System.out.println("sq.pop()="+t);
char q=t.charAt(0);
//System.out.println("x.charAt(i)="+x.charAt(i));
if(x.charAt(i)==q)
++l;
}
}
//System.out.println("index="+index);
//System.out.println("l="+l);
return l==x.length()?true:false;
}//ishu
public static void main(String[] args)throws Exception{
Scanner sc=new Scanner(System.in);
System.out.println("请输入要判断的字符串:");
String s=new String();
s=sc.nextLine();
Ishuiwen hui=new Ishuiwen();
boolean a=hui.ishui(s);
System.out.println("您输入的字符串:"+s+" ?回文:"+a);
}
}

结果:

请输入要判断的字符串:
ghasrharhahhahrthrsahg
您输入的字符串:ghasrharhahhahrthrsahg ?回文:false

3.设计一个将十进制数转化为二进制的方法。

代码:

package exercise;
import stack.Linkstack;
import java.util.Scanner;
public class JZzh {
public void sh2er(int a)throws Exception{
Linkstack s=new Linkstack();
while(a/2!=0){
int t=a%2;//取余数为低位做push操作
s.push(t);
a=a/2;
}
if(a!=0)//最高为不为0,则再次执行push操作
s.push(a);
String er=new String();
while(s.peek()!=null)//输出栈中的元素,逆置
er=er.concat(s.pop().toString());
System.out.println("转换后的二进制整数为:"+er);
}
public static void main(String[] args)throws Exception{
JZzh jinzhi=new JZzh();
Scanner sc=new Scanner(System.in);
System.out.println("请输入要转换的十进制整数:");
int b=sc.nextInt();
jinzhi.sh2er(b);
}
}

结果:

请输入要转换的十进制整数:
16
转换后的二进制整数为:10000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: