链接:
https://www.nowcoder.net/questionTerminal/baefd05def524a92bcfa6e1f113ed4f0
来源:牛客网
来源:牛客网
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
import java.util.*;
public class Main {
/**
* @param args
*/
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args){
ListNode p1 = new ListNode(1);
p1.next = new ListNode(2);
p1.next.next = new ListNode(3);
p1.next.next.next = new ListNode(2);
p1.next.next.next.next = new ListNode(1);
System.out.println(isPalindrome(p1));
}
public static boolean isPalindrome(ListNode pHead) {
// write code here
ListNode slow = pHead;
ListNode fast = pHead;
StringBuffer on1 = new StringBuffer();
StringBuffer on2 = new StringBuffer();
while(true){
if(fast.next==null){
break;
}
if(fast.next.next==null){
slow = slow.next;
break;
}
on1.append(slow.val);
slow = slow.next;
fast = fast.next.next;
}
slow = slow.next;
while(slow!=null){
on2.append(slow.val);
slow = slow.next;
}
on1.reverse();
return on1.toString().equals(on2.toString());
}
}