實現思路:藉助兩個快慢指針來實現,快指針走兩步,慢指針走一步,當快指針到終點時,慢指針剛好到中點,並且在慢指針每走一步中,將其指向方向修改,最後對比前後即可判斷是否爲迴文字符串。
public class Palindrome { static class ListNode{ int var; ListNode next; public ListNode(int x) { this.var = x; } } public static boolean isPalindrome(ListNode head){ if(head ==null || head.next==null){ return true; } //先找到鏈表的中間節點,使用兩個快慢指針:快指針移動兩步,慢指針移動一步 ListNode pre = null; ListNode fast = head; ListNode slow = head; while (fast !=null && fast.next !=null) { fast = fast.next.next; ListNode next = slow.next; slow.next = pre; pre = slow; slow = next; } if(fast !=null){ fast = fast.next; } //這時得到的pre和slow都是在中點 while (slow !=null) { if(slow.var != pre.var){ return false; } slow = slow.next; pre = pre.next; } return true; } }
測試:
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String tmp=in.nextLine();
char[] s=tmp.toCharArray();
ListNode[] node=new ListNode[s.length];
for(int i=0;i<s.length;i++){
node[i]=new ListNode(s[i]);
}
for(int i=0;i<s.length;i++){
if(i==s.length-1){ //最後一個節點,指針指向空
node[i].next=null;
}
else node[i].next=node[i+1];
}
boolean flag=Palindrome.isPalindrome(node[0]);
System.out.println("鏈表是迴文嗎? "+flag);
}