本次面试答案,以及收集到的大厂必问面试题分享:
先使用快慢指针,得到中间节点,然后反转 中间后半部分 链表节点,然后就是判断回文
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null){
return true;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while(head!=slow){
if(head.val != slow.val){
return false;
}
if(head.next == slow){
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}
解法二 - 通过将链表节点的val值 存入 顺序表/数组 中, 通过数组下标进行对比。
==========================================================================================================
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
ListNode currentNode = head;
while(currentNode != null){
list.add(currentNode.val);
currentNode = currentNode.next;
}
int front = 0;
int back = list.size()-1;
while(front < back){
if(list.get(front) != list.get(back) ){
return false;
}
front++;
back--;
}
return true;
}
}
=======================================================================
总结
这个月马上就又要过去了,还在找工作的小伙伴要做好准备了,小编整理了大厂java程序员面试涉及到的绝大部分面试题及答案,希望能帮助到大家
]