0
点赞
收藏
分享

微信扫一扫

LeetCode-234-回文链表

颜路在路上 2021-09-28 阅读 63
LeetCode

回文链表

解法一:链表遍历
import java.util.Stack;

public class LeetCode_234 {
public static boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode cur = head;
// 链表节点的个数
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
// 将前面的一半节点放入栈中
Stack<Integer> temp = new Stack<>();
ListNode newCur = head;
for (int i = 1; i <= count / 2; i++) {
temp.push(newCur.val);
newCur = newCur.next;
}
int start;
if (count % 2 == 0) {
start = count / 2 + 1;
} else {
start = count / 2 + 2;
newCur = newCur.next;
}
for (int i = start; i <= count; i++) {
if (temp.pop() != newCur.val) {
return false;
}
newCur = newCur.next;
}

return true;
}

public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(0);
head.next.next = new ListNode(1);

System.out.println(isPalindrome(head));
}
}
举报

相关推荐

0 条评论