一、题目名称java
Palindrome Linked List(回文链表)node
二、题目地址测试
https://leetcode.com/problems/palindrome-linked-list/优化
三、题目内容code
英文:Given a singly linked list, determine if it is a palindrome.递归
中文:给出一个链表,肯定该链表是否为回文链表,即先后对称的链表leetcode
四、解题方法1开发
第一种方式是建立一个逆序的链表,而后分别从前向后遍历正序和逆序两个链表,逐个节点进行比较。get
Java代码以下:it
/** * @功能说明:LeetCode 234 - Palindrome Linked List * @开发人员:Tsybius2014 * @开发时间:2015年12月18日 */ public class Solution { /** * 测试链表是否为回文链表 * @param head 链表首节点 * @return */ public boolean isPalindrome(ListNode head) { //建立一个逆序的链表 ListNode node = head; ListNode tail = null; while (node != null) { ListNode temp = new ListNode(node.val); temp.next = tail; tail = temp; node = node.next; } //比对原链表与逆序链表是否一致 while (tail != null) { if (tail.val != head.val) { return false; } head = head.next; tail = tail.next; } return true; } }
这个代码能够优化一下,即在和建立的逆序链表作比较时,之比较一半的节点就能够了
Java代码以下:
/** * @功能说明:LeetCode 234 - Palindrome Linked List * @开发人员:Tsybius2014 * @开发时间:2015年12月18日 */ public class Solution { /** * 测试链表是否为回文链表 * @param head 链表首节点 * @return */ public boolean isPalindrome(ListNode head) { //建立一个逆序的链表 ListNode node = head; ListNode tail = null; int counter = 0; while (node != null) { ListNode temp = new ListNode(node.val); temp.next = tail; tail = temp; node = node.next; counter++; } counter /= 2; //比对原链表与逆序链表是否一致 while (counter != 0) { counter--; if (tail.val != head.val) { return false; } head = head.next; tail = tail.next; } return true; } }
五、解题方法2
另外一种方式是从讨论区看到的方法,这个方法使用递归解决本问题,可将空间复杂度控制在O(1)
Java代码以下:
/** * @功能说明:LeetCode 234 - Palindrome Linked List * @开发人员:Tsybius2014 * @开发时间:2015年12月18日 */ public class Solution { ListNode temp; /** * 测试链表是否为回文链表 * @param head 链表首节点 * @return */ public boolean isPalindrome(ListNode head) { temp = head; return isPalindromeList(head); } /** * 测试链表是否为回文链表 * @param node 链表首节点 * @return */ private boolean isPalindromeList(ListNode node) { if (node == null) { return true; } boolean result = isPalindromeList(node.next) && (temp.val == node.val); temp = temp.next; return result; } }
END