题目一:回文链表
思路:首先利用递归将链表倒序添加到集合中,接着遍历链表将其与集合中的元素进行比较,如果有不相等的,则返回false,如果都相等,返回true。
代码:
import java.util.ArrayList;
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 Main18 {
public static ArrayList<Integer> arr;
public static void main(String[] args) {
ListNode l6=new ListNode(1, null);
ListNode l5=new ListNode(2, l6);
ListNode l4=new ListNode(3, l5);
ListNode l3=new ListNode(3, l4);
ListNode l2=new ListNode(2, l3);
ListNode l1=new ListNode(1, l2);
System.out.println(isPalindrome(l1));
}
public static void copy(ListNode head) {
if(head!=null) {
copy(head.next);
arr.add(head.val);
}
}
public static void prnt(ListNode head) {
if(head!=null) {
System.out.println(head.val);
prnt(head.next);
}
}
public static boolean isPalindrome(ListNode head) {
boolean flag=true;
arr=new ArrayList<Integer>();
copy(head);
int index=0;
while(head!=null) {
if(head.val!=arr.get(index)) {
flag=false;
break;
}
head=head.next;
index++;
}
return flag;
}
}
运行成功截图: