题解 | #牛群编号的回文顺序#
牛群编号的回文顺序
https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return bool布尔型
*/
public boolean isPalindrome (ListNode head) {
// write code here
if(head == null || head.next == null) return true;
//使用栈存放链表一半的数据
Stack<Integer> stack = new Stack<>();
//使用快慢指针
ListNode slow = head,fast = head;
while(fast != null && fast.next != null){
//将前一般的数据存放在栈中
stack.push(slow.val);
//用快慢指针来定位后一半的数据位置
fast = fast.next.next;
slow = slow.next;
}
if(fast != null){
slow = slow.next;
}
//将后一半的数据与前一半的数据进行对比
while(slow != null){
int num = stack.pop();
//只要有一次是不等的,则直接返回false;
if(slow.val != num) return false;
slow = slow.next;
}
//只有全部都满足条件才会返回true;
return true;
}
}
本题的解题思路是使用:栈和快慢指针
查看9道真题和解析