您的位置:首页 > 其它

Cracking the Coding Interview Q2.7

2014-07-08 00:23 281 查看
检测链表是否是palindrome.

思路1:翻转并比较。

思路2:迭代。

思路3:递归。

public static boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;

Stack<Integer> stack = new Stack<Integer>();

while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}

/* Has odd number of elements, so skip the middle */
if (fast != null) {
slow = slow.next;
}

while (slow != null) {
int top = stack.pop().intValue();
System.out.println(slow.data + " " + top);
if (top != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}

public Question.Result isPalindromeRecurse(LinkedListNode head, int length) {
if (head == null || length == 0) {
return new Question.Result(null, true);
} else if (length == 1) {
return new Question.Result(head.next, true);
} else if (length == 2) {
return new Question.Result(head.next.next, head.data == head.next.data);
}
Question.Result res = isPalindromeRecurse(head.next, length - 2);
if (!res.result || res.node == null) {
return res; // Only "result" member is actually used in the call stack.
} else {
res.result = head.data == res.node.data;
res.node = res.node.next;
return res;
}
}

public boolean isPalindrome(LinkedListNode head) {
int size = 0;
LinkedListNode n = head;
while (n != null) {
size++;
n = n.next;
}
Result p = isPalindromeRecurse(head, size);
return p.result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: