码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 234. 回文链表 java

时间:2019-11-25 11:18:29      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:style   null   init   时间   空间   bsp   java   题目   def   

题目:

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解题:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {    //画个图走一遍就懂了
        if(head == null || head.next == null) {
            return true;
        }
        ListNode slow = head, fast = head;    //快慢指针找到链表的中间位置
        ListNode pre = head, prepre = null;//专门设立两个指针用于反转链表
        while(fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
            pre.next = prepre;    //反转前半部分链表
            prepre = pre;
        }
        if(fast != null) {    //对准中点
            slow = slow.next;
        }
        while(pre != null && slow != null) {
            if(pre.val != slow.val) {
                return false;
            }
            pre = pre.next;
            slow = slow.next;
        }
        return true;
    }
}

 

leetcode 234. 回文链表 java

标签:style   null   init   时间   空间   bsp   java   题目   def   

原文地址:https://www.cnblogs.com/yanhowever/p/11926471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!