Algorithms—234.Palindrome Linked List

来源:互联网 发布:大连理工大学 知乎 编辑:程序博客网 时间:2024/06/15 09:00

思路:快慢双指针扫描,找到中点,从中点开始原地翻转,拿翻转后的进行比较,注意比较的终止条件用翻转后的为空,不然需要判断原链表长度的奇偶性。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public boolean isPalindrome(ListNode head) {        if (head==null||head.next==null) {return true;}        ListNode slow=head;        ListNode fast=head;        while (fast!=null&&fast.next!=null) {slow=slow.next;fast=fast.next.next;}        ListNode test=f(slow);        while (test!=null) {if (test.val!=head.val) {return false;}test=test.next;head=head.next;}                return true;    }    //原地翻转链表    public ListNode f(ListNode node){    if (node==null||node.next==null) {return node;}    ListNode l=node.next;    ListNode h;    node.next=null;    while (l!=null) {h=l.next;l.next=node;node=l;l=h;}    return node;    }}


0 0
原创粉丝点击