234. Palindrome Linked List
234. Palindrome Linked List
初雪之音 发表于1年前
234. Palindrome Linked List
  • 发表于 1年前
  • 阅读 5
  • 收藏 0
  • 点赞 0
  • 评论 0

【腾讯云】买域名送云解析+SSL证书+建站!>>>   

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
		boolean result = true;

		if (head != null && head.next != null) {
			ListNode slow = head;
			ListNode fast = head;
			while (fast != null && fast.next != null) {
				slow = slow.next;
				fast = fast.next.next;
			}
			if (fast != null) {
				slow = slow.next;
			}
			slow = reverse(slow);
			fast = head;
			while (slow != null) {
				if (fast.val != slow.val) {
					result = false;
					break;
				}
				fast = fast.next;
				slow = slow.next;
			}
		}

		return result;
	}

	public ListNode reverse(ListNode head) {
		ListNode result = null;

		ListNode pre = null;
		while (head != null) {
			ListNode tempNext = head.next;
			head.next = pre;
			pre = head;
			head = tempNext;
		}
		result = pre;

		return result;
	}
}

 

标签: leetcode
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 41
博文 242
码字总数 136279
×
初雪之音
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: