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

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

sq.push(x[i]);

}

while(!sq.isEmpty()){

for(int i=0;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[n];

System.out.println("请输入数组的元素:");

for(int i=0;i

ar[i]=sc.nextInt();

}

System.out.print("逆置之前的数组为: ");

for(int i=0;i

System.out.print(ar[i]+" ");

}

nizhi a=new nizhi();

a.shunizhi(ar);

System.out.print(" 逆置操作之后的数组为");

for(int i=0;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

sq.push(x.charAt(index));

//System.out.println(sq.peek());

index++;

}

for(int i=0;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

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值