您的位置:首页 > 编程语言 > C语言/C++

Palindrome Linked List

2016-06-07 17:16 323 查看

c++

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return true;

ListNode* fast = head, *slow = head;
while (fast!=nullptr && fast->next!=nullptr) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* node = nullptr;
while (slow) {
ListNode* nxt = slow->next;
slow->next = node;
node = slow;
slow = nxt;
}

while (node!=nullptr && head!=nullptr) {
if (node->val != head->val)
return false;
node = node->next;
head = head->next;
}
return true;
}
};


python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return True

fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next

node = None
while slow:
nxt = slow.next
slow.next = node
node = slow
slow = nxt

while node:
if node.val != head.val:
return False
node = node.next
head = head.next

return True


reference:

https://leetcode.com/discuss/46304/python-understand-solution-comments-operate-nodes-directly
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言