3.27练习题

题目一:回文链表

思路:首先利用递归将链表倒序添加到集合中,接着遍历链表将其与集合中的元素进行比较,如果有不相等的,则返回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;
     }
}

运行成功截图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值