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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律