prosto.mail
BAN USERboolean hasAddTo12(int... a) {
HashSet<Integer> set = new HashSet<>(a.length);
for (int x : a) {
if (set.contains(12 - x)) {
return true;
} else {
set.add(x);
}
}
return false;
}
boolean isPalindrome(char[] w) {
int s = 0;
int e = w.length - 1;
while (e >= s) {
while (!Character.isAlphabetic(w[s]) && e > s) {
s++;
}
while (!Character.isAlphabetic(w[e]) && e > s) {
e--;
}
if (w[s] != w[e]) return false;
s++;
e--;
}
return true;
}
public static class Node {
public Node(String value) {
this.value = value;
}
public String value;
public List<Node> children = new ArrayList<>();
}
public static void printTreeByLevels(Node root){
List<Node> rootLevel = new ArrayList<>();
rootLevel.add(root);
printLevel(rootLevel);
}
public static void printLevel(List<Node> level){
List<Node> nextLevel = new ArrayList<>();
for (Node n : level){
System.out.printf("%s ", n.value);
nextLevel.addAll(n.children);
}
if (!nextLevel.isEmpty()) {
System.out.println("\n");
printLevel(nextLevel);
}
}
Another solution based on split/merge linked list
public static Node swapInPairs(Node head) {
if (head == null || head.next == null) {
return head;
}
Node head2 = head.next;
Node t1 = head;
Node t2 = head2;
while (t1 != null && t2 != null) {
t1.next = t2.next;
t2.next = t2.next != null ? t2.next.next : null;
t1 = t1.next;
t2 = t2.next;
}
Node t = head2;
Node c1 = head;
Node c2 = head2.next;
while (c1 != null || c2 != null) {
if (c1 != null) {
t.next = c1;
t = t.next;
c1 = c1.next;
}
if (c2 != null) {
t.next = c2;
t = t.next;
c2 = c2.next;
}
}
return head2;
}
}
Can we use just simple add/remove API?
static void swapInPairs(LinkedList list){
int N = list.size();
int last = N - (N%2) - 1;
for (int i = 1; i <= last; i = i + 2){
list.add(i-1, list.remove(i));
}
}
Note: root node can be changed, and eventually it will be the first node we have to print.
- prosto.mail May 07, 2015