2.6 Palindrome
2015-10-27 06:46
197 查看
1. Reverse and Compare:
2. Using extra space ( stack)
ListNode* reverseList(ListNode* head){ if(!head) return head; ListNode* pre = NULL; while (head) { ListNode* tmp = head->next; head->next = pre; pre = head; head = tmp; } return pre; } bool isPalindrome(ListNode* head){ if(!head || !head->next) return true; ListNode* fast = head; ListNode* slow = head; while (fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; } slow->next = reverseList(slow->next); slow = slow->next; while (slow){ if(head->val != slow->val) return false; slow = slow->next; head = head->next; } return true; }
2. Using extra space ( stack)
bool isPalindrome(ListNode* head){ stack<int> stk; if(!head || !head->next) return true; ListNode* fast = head; ListNode* slow = head; while(fast && fast->next){ stk.push(slow->val); fast = fast->next->next; slow = slow->next; } if(fast) slow = slow->next;//if the list has odd length we skip middle point; while(slow || !stk.empty()){ if(slow->val != stk.top()) return false; slow = slow->next; stk.pop(); } return true; }
相关文章推荐
- 解析Java中的队列和用LinkedList集合模拟队列的方法
- JAVA LinkedList和ArrayList的使用及性能分析
- LinkedList学习示例模拟堆栈与队列数据结构
- ArrayList和LinkedList的主要区别
- Java数据结构-线性表之单链表LinkedList
- ARRAYLIST VECTOR LINKEDLIST 区别与用法(2014-10-14)
- Remove Duplicates from Sorted List II
- Reverse Linked List
- Reverse Linked List II
- Partition List
- android性能之List
- Remove Nth Node From End of List
- Remove Duplicates from Sorted List
- Merge Two Sorted Lists
- ArrayList Vector LinkedList 区别与用法
- 黑马程序员————List集合概述、Arrayist集合、Vector集合、LinkedList集合简述
- 单向链表LinkedList的使用
- [Leetcode题解]002 Add Two Numbers
- LinkedList与ArrayList的区别
- Activity回退研究