首页 > 其他 > 详细

LeetCode——回文链表

时间:2019-12-22 23:31:59      阅读:77      评论:0      收藏:0      [点我收藏+]

题目

给定一个链表的头节点head,请判断该链表是否为回 文结构。
例如: 1->2->1,返回true。
1->2->2->1,返回true。
15->6->15,返回true。
1->2->3,返回false。
进阶:
如果链表长度为N,时间复杂度达到O(N),额外空间复杂 度达到O(1)。

 

代码实现:

//快慢指针,都是从头开始

public class IsPalindromeList {
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;
}
}

class ListNode {
int val;
// 下一个链表对象
ListNode next;
//赋值链表的值
ListNode(int x) { val = x; }

}
代码实现2:
//快慢指针,反转前半部分链表,时间O(n),空间O(1)
/**用2个指针,一个low,一个fast,fast是low的2倍,所以可以达到2分链表的效果
*,在移动指针时同时对前半部分链表进行反转。最后直接比较被分开的2个链表
*因为不能改变当前slow的next,不然就无法跳到下一个元素,所以这里用pre和prepre实现指针的反转
*时间复杂度:第一个循环O(n/2),第2个循环O(n/2)
*/
 
public class IsPalindromeList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode slow = head, fast = head.next, pre = null, prepre = null;
while(fast != null && fast.next != null) {
//反转前半段链表
pre = slow;
slow = slow.next;
fast = fast.next.next;
//先移动指针再来反转
pre.next = prepre;
prepre = pre;
}
ListNode p2 = slow.next;
slow.next = pre;
ListNode p1 = fast == null? slow.next : slow;
while(p1 != null) {
if(p1.val != p2.val) {
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}

}

class ListNode {
int val;
// 下一个链表对象
ListNode next;
//赋值链表的值
ListNode(int x) { val = x; }

}
 

LeetCode——回文链表

原文:https://www.cnblogs.com/cdlyy/p/12081579.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!