Skip to content

Instantly share code, notes, and snippets.

@forkercat
Last active March 31, 2019 02:37
Show Gist options
  • Save forkercat/1db0dde99088829bf62281dc827154e3 to your computer and use it in GitHub Desktop.
Save forkercat/1db0dde99088829bf62281dc827154e3 to your computer and use it in GitHub Desktop.
recursive version of catenate
public class IntList {
public int first;
public IntList rest;
public IntList(int first0, IntList rest0) {
first = first0;
rest = rest0;
}
/**
* Returns a list consisting of the elements of A followed by the
* * elements of B. May NOT modify items of A. Use 'new'.
*/
public static IntList catenate(IntList A, IntList B) {
IntList M = null;
IntList p = null;
if (A != null) {
M = new IntList(A.first, null);
p = M;
A = A.rest;
while (A != null) {
p.rest = new IntList(A.first, null);
p = p.rest;
A = A.rest;
} /* now p points to the last element of A */
} else if (B != null) { /* A == null */
// if (A == null && B != null) { /* this line is bug. A is changed */
M = new IntList(B.first, null);
p = M;
B = B.rest;
}
while (B != null) { /* can't put this block inside the above block */
p.rest = new IntList(B.first, null);
p = p.rest;
B = B.rest;
}
return M;
}
/**
* catenate - recursive
*/
public static IntList catenate_re(IntList A, IntList B) {
if (A == null) {
/* Enter B mode! later A should be null always */
if (B == null) {
return null;
}
return new IntList(B.first, catenate_re(null, B.rest));
} else {
/* Enter A mode! later B stays the same */
return new IntList(A.first, catenate_re(A.rest, B));
}
}
public static main(String[] args) {
IntList L1 = IntList.of(1, 2, 3, 4, 5);
IntList L2 = IntList.of(6, 7);
System.out.println(catenate_re(L1, L2));
}
// ----------------------------------------------------------------------
public static IntList of(Integer... args) {
IntList result, p;
if (args.length > 0) {
result = new IntList(args[0], null);
} else {
return null;
}
int k;
for (k = 1, p = result; k < args.length; k += 1, p = p.rest) {
p.rest = new IntList(args[k], null);
}
return result;
}
@Override
/** Outputs the IntList as a String. You are not expected to read
* or understand this method. */
public String toString() {
Formatter out = new Formatter();
String sep;
sep = "(";
int cycleLocation = detectCycles(this);
int cnt = 0;
for (IntList p = this; p != null; p = p.rest) {
out.format("%s%d", sep, p.first);
sep = ", ";
cnt++;
if ((cnt > cycleLocation) && (cycleLocation > 0)) {
out.format("... (cycle exists) ...");
break;
}
}
out.format(")");
return out.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment