回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
作者:力扣 (LeetCode)
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnv1oc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
package leetCode;
public class lianbiaohuiwen {
public static boolean isPalindrome(ListNode head) {
ListNode newnode = new ListNode();
newnode = head;
int count = 1;
while(newnode.next!=null){
count++;
newnode = newnode.next;
}
if(count==1)return true;
int[] shuzu = new int[count];
//遍历获得数组长度
for(int i=0;i<shuzu.length;i++){
shuzu[i] = head.val;
head = head.next;
}
int start = 0,end = shuzu.length-1;
//双指针进行判断当重合的时候数据是否都一致
while(start<end){
if(shuzu[start]!=shuzu[end]){
return false;
}
start++;
end--;
}
return true;
}
public static void main(String[] args) {
//构造模拟数据
ListNode head = new ListNode(1);
ListNode firstNode = new ListNode(1);
ListNode secondNode = new ListNode(2);
ListNode thirdNode = new ListNode(1);
head.next = firstNode;
firstNode.next = secondNode;
secondNode.next = thirdNode;
boolean ishuiwen = isPalindrome(head);
System.out.println(ishuiwen);
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}