反转字符的字符串顺序,并使用构造函数放置到LinkedList中 [英] Reverse String order of characters and place into LinkedList using a constructor

查看:51
本文介绍了反转字符的字符串顺序,并使用构造函数放置到LinkedList中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序接受一个String并将其以相反的顺序放入LinkedList中.

此代码似乎无效(输入错误),我不知道为什么.有解决方案吗?

  public LargeInteger(字符串输入){去做size = size + input.length();LLNode< Integer>curNode = new LLNode< Integer>();for(int curPos = input.length()-1; curPos> = 0; curPos--){if(curPos == input.length()-1){head = new LLNode< Integer>();head.data = input.charAt(curPos)+'0';curNode = head;}别的{curNode.link = new LLNode< Integer>();curNode = curNode.link;curNode.data = input.charAt(curPos)+'0';}}} 

解决方案

欢迎使用堆栈溢出.

如何使用List接口和String类的方法,而不是仅仅用于循环?检查以下示例:

 字符串短语=这是短语";//这是输入List< String>list = new LinkedList<>();//以递减的索引顺序迭代输入for(int i = phrase.length()-1; i> = 0; i--){//从输入中获取字符并添加到LinkedListlist.add(Character.toString(phrase.charAt(i)));} 

如果不想添加空格,请在添加字符之前添加 if(isEmpty(phrase.charAt(i)))继续; .

实时示例此处.

I am making a program that takes a String and puts it in the opposite order into a LinkedList.

This code doesn't seem to work (wrong input), and I can't figure out why. Any solutions?

public LargeInteger(String input) 
{
     TODO
    size=size+input.length();
    LLNode<Integer> curNode=new LLNode<Integer>();
    for(int curPos=input.length()-1;curPos>=0;curPos--)
    {
        if(curPos==input.length()-1)
        {
            head=new LLNode<Integer>();
            head.data=input.charAt(curPos)+'0';
            curNode=head;
        }
        else
        {
            curNode.link=new LLNode<Integer>();
            curNode=curNode.link;
            curNode.data=input.charAt(curPos)+'0';
        }
    }
}

解决方案

Welcome to Stack Overflow.

What about to use the methods of List interface and String class, instead of just for loops? Check this example:

String phrase = "this is the phrase"; // this is the input
List<String> list = new LinkedList<>();

// iterates the input in decreasing index order
for(int i=phrase.length()-1; i >= 0; i--) { 
    // gets the character from the input and add to the LinkedList
    list.add(Character.toString(phrase.charAt(i))); 
}

If you want not to add white spaces, add if(isEmpty(phrase.charAt(i))) continue; before adding the character.

Live example here.

这篇关于反转字符的字符串顺序,并使用构造函数放置到LinkedList中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆