leetcode - 234. 回文链表

234. 回文链表

public boolean isPalindrome(ListNode head) {
return twoPoint(head);
//return withStack(head);
}
//找中点, 反转后一部分链表
public boolean twoPoint(ListNode head) {
//得中点
ListNode mid = getMid(head);
//得到反转的头, 从中点下一个开始反转链表
ListNode reverseHead = reverse(mid.next);
//让反转的头和尾一起移动看看是不是回文
while (head != null && reverseHead != null) {
if(head.val != reverseHead.val){
return false;
}
head = head.next;
reverseHead = reverseHead.next;
}
//还原链表
mid.next = reverse(reverseHead);
return true;
}
//快慢指针得中点
public ListNode getMid(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return head;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//反转列表
public ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//使用栈迭代
public boolean withStack(ListNode head){
if(head == null){
return false;
}
//把所有的node全都加到栈里
Deque<Integer> stack = new LinkedList<>();
ListNode cur = head;
while(cur != null){
stack.push(cur.val);
cur = cur.next;
}
//逐个弹出跟链表当前节点的val对比
ListNode compare = head;
while(compare != null){
if(stack.pop() != compare.val){
return false;
}
compare = compare.next;
}
return true;
}

 

posted on   老菜农  阅读(19)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

统计信息

点击右上角即可分享
微信分享提示