本文主要是介绍*Leetcode 234. Palindrome Linked List,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/palindrome-linked-list/description/
有点意思。。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:int getLen(ListNode* head) {int ret = 0;while (head) {ret ++;head = head->next;}return ret;}ListNode* reverse(ListNode* head) {if (!head) return head;ListNode* pre = NULL, *tmp = NULL, *cur = head;while (cur) {tmp = cur -> next;cur ->next = pre;pre = cur;cur = tmp;}return pre;}bool isPalindrome(ListNode* head) {int len = getLen(head);// if (len%2)int half = len/2;ListNode* cur = head;while (half--) cur = cur->next;if (len%2) {// cur->next = NULL;// ListNode* tmp = cur;cur = cur->next;// tmp->next = NULL;} cur = reverse(cur);// cout << "cur->val:" << cur->val << endl;while (cur) {if (cur->val != head->val) return false;cur = cur->next;head = head->next;}return true;}
};
这篇关于*Leetcode 234. Palindrome Linked List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!