使用尾插法创建链表并实现判断回文链表
import java.util.Scanner;
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 static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ListNode newNode = new ListNode();
ListNode head = newNode;
head.next = null;
ListNode tail = head;
while(sc.hasNext()){
int val = sc.nextInt();
if(val == -1){
break;
}
ListNode nextNode = new ListNode(val);
tail.next = nextNode;
tail = nextNode;
}
System.out.println(isPalindrome(head.next));
}
public static boolean isPalindrome(ListNode head){
ListNode slow = head;
ListNode fast = head;
ListNode temp = null;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
while(fast != null){
temp = fast.next;
fast.next = slow;
slow = fast;
fast = temp;
}
temp = slow;
fast = head;
boolean res = true;
while(slow != null && fast != null){
if(slow.val != fast.val){
res = false;
break;
}
slow = slow.next;
fast = fast.next;
}
slow = temp.next;
temp.next = null;
while(slow != null){
fast = slow.next;
slow.next = temp;
temp = slow;
slow = fast;
}
return res;
}
}
