`

LeetCode 234 - Palindrome Linked List

 
阅读更多

Given a singly linked list of characters, write a function that returns true if the given list is palindrome, else false.

METHOD 1 (Use a Stack)
A simple solution is to use a stack of list nodes. This mainly involves three steps.
1) Traverse the given list from head to tail and push every visited node to stack.
2) Traverse the list again. For every visited node, pop a node from stack and compare data of popped node with currently visited node.
3) If all nodes matched, then return true, else false.

Time complexity of above method is O(n), but it requires O(n) extra space. Following methods solve this with constant extra space.

public boolean isListPalindrome(ListNode head) {
	Stack<ListNode> stack = new Stack<>();
	ListNode node = head;
	while(node != null) {
		stack.push(node);
		node = node.next;
	}
	while(head != null) {
		if(head.val != stack.pop().val) return false;
		head = head.next;
	}
	return true;
}

 

METHOD 2 (By reversing the list)
This method takes O(n) time and O(1) extra space.
1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are identical.
4) Construct the original linked list by reversing the second half again and attaching it back to the first half

public boolean isListPalindrome(ListNode head) {
	if(head==null || head.next==null) return true;
	ListNode walker = head, runner = head;
	while(walker!=null && runner!=null) {
		walker = walker.next;
		runner = runner.next;
		if(runner!=null) {
			runner = runner.next;
		}
	}
	ListNode h = reverseLinkedList(walker);
	while(h!=null && head!=null) {
		if(h.val != head.val) return false;
		h = h.next;
		head = head.next;
	}
	return true;
}

public ListNode reverseLinkedList(ListNode head) {
	ListNode dummy = new ListNode(0);
	ListNode pre = dummy;
	while(head != null) {
		ListNode next = head.next;
		head.next = pre.next;
		pre.next = head;
		head = next;
	}
	return dummy.next;
}

重构了下代码:

public boolean isPalindrome(ListNode head) {
    if(head == null || head.next == null) return true;
    ListNode slow = head, fast = head.next;
    while(fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next;
        if(fast != null) fast = fast.next;
    }
    ListNode h = slow.next;
    slow.next = null;
    while(h != null) {
        ListNode next = h.next;
        h.next = slow.next;
        slow.next = h;
        h = next;
    }
    ListNode l1 = head, l2 = slow.next;
    while(l2 != null) {
        if(l1.val != l2.val) return false;
        l1 = l1.next;
        l2 = l2.next;
    }
    return true;
}

 

另外,还可以用递归的方法。

递归方法参见:

http://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/

分享到:
评论

相关推荐

    Leetcode 234. Palindrome Linked List

    方法1  思路:将链表中的元素都保存list中,并判断这个list和反转后的list,是否相同,如果相同,则回文;否则,则不回文。...# Definition for singly-linked list. # class ListNode(object): # def __i

    gasstationleetcode-leetcode-in-niuke:在牛客网上的在线编程中的leetcode在线编程题解

    linked-list-cycle-ii 链表 linked-list-cycle 链表 copy-list-with-random-pointer 复杂度 single-number 动态规划 candy 贪心 gas-station 动态规划 palindrome-partitioning-ii 动态规划 triangle 树 sum-root-to...

    leetcode卡-leetcode:利特码解决方案

    Palindrome linked list Linked List Cycle trees Convert Sorted Array to Binary Search Tree string and search First Bad Version Dynamic Programing *** Climbing Stairs Set Matrix Zeroes API System....

    leetcode2sumc-LeetCode:LeetCode的一些题目

    leetcode 2 sum c LeetCode 帮助文档 帮助文档存放在Help文件夹下。 文件名 文件描述 ...complexitypython.txt Python的一些常规操作的复杂度统计 ...Linked List(链表) ...List ...Linked ...Palindrome Linked List

    leetcode338-Leetcode:一些过滤leetcode问题的解决方案

    234.Palindrome 链表: | 725. 分部分拆分链表: | 328.奇偶链表:| 哈希表: 问题及解决方法: 1.二和:| 594.最长和谐子序列:| 128.最长连续序列:| 数组和矩阵 问题及解决方法: 283.移零:| 566.重塑矩阵: | ...

    leetcode中325题python-leetcode:leetcode

    reverse-linked-list-ii(Reverse a Sub-list) 141 环形链表 linked-list-cycle 142 环形链表 II linked-list-cycle-ii 143 重排链表 reorder-list 148 排序链表 sort-list 234 回文链表 palindrome-linked-list 双...

    LeetCode最全代码

    * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap]...

    LeetCode3 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with...

    javalruleetcode-leetcode:力码解决方案

    [回文链表](md/Palindrome Linked List.md) - 2015-10-06 [数字一](md/数字一.md) - 2015-10-06 [使用栈实现队列](md/使用栈实现队列.md) - 2015-10-06 [BST 中的第 K 个最小元素](md/BST.md 中的第 K 个最小元素) -...

    cpp-算法精粹

    Palindrome Linked List 字符串 Valid Palindrome Implement strStr() String to Integer (atoi) Add Binary Longest Palindromic Substring Regular Expression Matching Wildcard Matching Longest Common Prefix ...

    javalruleetcode-JavaInterviewChecklist:要检查的Java事项

    leetcode 面试清单 Java 比较器与比较器 哈希 静止的 例外 线 泛型 算法 链表 Linked List Cycle Remove Nth Node From End of List Merge Two Sorted Lists 两个链表的交集 Remove Duplicates from Sorted List ...

    leetcodepython001-Algorithm:关于数据结构和算法的问题(Leetcode、编程之美和课程作业)

    Palindrome Number C++ 2016/4/26 Easy 044 Wildcard Matching Python 2016/4/1 Hard 051 N-Queens C++ 2016/5/18 Hard 092 Reverse Linked List II Python 2017/11/28 Medium 095 Unique Binary Search Trees ...

Global site tag (gtag.js) - Google Analytics