(java)Palindrome Linked List
java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料
保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?思路:本题题意是判断一个链表是否是回文链表,注意本题要求空间复杂度是0(1),所以不能借助其它的容器。先遍历一遍此链表,得到此链表的长度,然后将链表的后半部分转置。设置两个指针p,q分别指向前半部分链表的开始节点和后半部分链表的开始节点,判断前半部分链表是否和后半部分链表相同,相同就是回文链表,不同就不是。
代码如下(已通过leetocde)
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null) return true;
ListNode temp=head;
int length=0;
while(temp!=null){
length++;
temp=temp.next;
}
ListNode q=head;
int count=1;
while(count<=length/2) {
q=q.next;
count++;
}
//System.out.println(q.val);
ListNode current=q;
ListNode pleft=null;
ListNode pright=null;
while(current!=null) {
pright=current.next;
current.next=pleft;
pleft=current;
current=pright;
}
ListNode laterhead=pleft;
while(laterhead!=null) {
if(laterhead.val!=head.val) return false;
else {
head=head.next;
laterhead=laterhead.next;
}
}
return true;
}
}
leetcodejavaPalindromeLinkedLi
因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。
后续会有更多的精彩的内容分享给大家。
支付宝扫一扫
微信扫一扫
