我正在练习基本的数据结构,我在递归方面遇到了一些困难.我理解如何通过迭代来做到这一点,但我通过递归从链接列表的最后一个返回第n个节点的所有尝试都导致为null.到目前为止这是我的代码:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
findnthToLastRecursion(node.next(), pos);
if(++i == pos) return node;
return null;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我理解我在哪里出错吗?
这是我的迭代解决方案,工作正常,但我真的想知道如何将其转换为递归:
public static Link.Node findnthToLast(Link.Node head, int n) {
if (n < 1 || head == null) {
return null;
}
Link.Node pntr1 = head, pntr2 = head;
for (int i = 0; i < n - 1; i++) {
if (pntr2 == null) {
return null;
} …Run Code Online (Sandbox Code Playgroud) 我正在努力开始练习面试问题,我遇到了这个问题:
将String aaaabbbbddd转换为a4b4d3
您基本上希望将现有字符串转换为每个唯一字符出现次数和字符出现次数的字符串.
这是我的解决方案,但我认为它可以被提炼成更优雅的东西:
String s = "aaaabbbbddd";
String modified = "";
int len = s.length();
char[] c = s.toCharArray();
int count = 0;
for (int i = 0; i < len; i++) {
count = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ') {
break;
}
if (c[i] == c[j]) {
count++;
c[j] = ' ';
}
}
if (c[i] != ' ') {
modified += c[i] + …Run Code Online (Sandbox Code Playgroud)