初级算法:回文链表

回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

package com.LinkList;

public class IsPalindrome5 {
	/*
	 * 思路一:想直接与反转链表进行比较,其中有几个注意点 (1)在进行指针赋值的时候最好不要直接指向别的指针,当同时便利的时候极易出错 (2)这种方法效率很低
	 */
	// public boolean isPalindrome(ListNode head) {
	// ListNode temp1 = new ListNode(head.val);
	// ListNode itr = head.next;
	// ListNode itr2 = temp1;
	// while(itr!=null) {
	// itr2.next = itr;
	// itr = itr.next;
	// }
	// ListNode reverse = reverse(head, head.next);
	// head.next = null;
	// while (temp1 != null && reverse != null) {
	// if (temp1.val != reverse.val)
	// return false;
	// temp1 = temp1.next;
	// reverse = reverse.next;
	// }
	// if (temp1 != null || reverse != null)
	// return false;
	// return true;
	// }
	//
	// public ListNode reverse(ListNode a, ListNode b) {
	// if (b.next == null) {
	// b.next = a;
	// return b;// 头部
	// }
	// ListNode tempNext = b.next;
	// b.next = a;
	// return reverse(b, tempNext);
	// }
	/*
	 * 思路二:首先遍历链表得到长度,然后反转一半的链表,在这个过程找到左右指针的起点,需要分奇偶
	 */
	public boolean isPalindrome(ListNode head) {
		ListNode itr = head;
		int count = 0;
		while (itr != null) {
			count++;
			itr = itr.next;
		}
		if (count == 1 || count == 0)
			return true;
		ListNode itr2 = head;
		int c = count % 2 == 0 ? count / 2 : (count / 2 + 1);
		System.out.println("c:" + c);
		while (c > 0) {
			c--;
			itr2 = itr2.next;
		}
		System.out.println(itr2.val + " ");
		ListNode reverse = reverse(head, head.next, count / 2 - 1);
		while (itr2 != null) {
			if (reverse.val != itr2.val)
				return false;
			reverse = reverse.next;
			itr2 = itr2.next;
		}
		return true;
	}

	public ListNode reverse(ListNode a, ListNode b, int c) {
		if (b == null || c <= 0) {
			System.out.println("此时的a:" + a.val);
			return a;
		}

		if (b.next == null) {
			b.next = a;
			return b;
		}
		ListNode tempNext = b.next;
		b.next = a;
		return reverse(b, tempNext, c - 1);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值