leetcode系列(16)判断链表是否为回文
来源:互联网 发布:中国移动网络测试 编辑:程序博客网 时间:2024/05/19 13:56
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
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) { return true; // IMHO this should be false but is true in leetcode oj } if (head->next == nullptr) { return true; } // get the len of the list int len = 0; for (auto ptr = head; ptr != nullptr; ptr = ptr->next) { len++; } // get the header of another half of the list int nl = len / 2; auto ptr = head; for (int i = 0; i != nl; ++i) { ptr = ptr->next; } if (len % 2 != 0) { ptr = ptr->next; } // reverse another half ListNode* pre = nullptr; auto cur = ptr; while (cur != nullptr) { auto post = cur->next; cur->next = pre; pre = cur; cur = post; } ptr = pre; // compare two half list for (int i = 0; i != nl; ++i) { if (ptr->val != head->val) { return false; } ptr = ptr->next; head = head->next; } return true; }};
Python代码
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): l = [] while head != None: l.append(head.val) head = head.next i = 0 j = len(l) - 1 while i < j: if l[i] != l[j]: return False i += 1 j -= 1 return True
0 0
- leetcode系列(16)判断链表是否为回文
- leetcode Palindrome Number (判断整数是否为回文)
- leetcode 用fast-slow 指针的方法判断链表是否为回文链表。
- [分析总结:leetcode-Palindrome Linked List] 给定单链表,判断链表是否为回文。
- 【Leetcode】234. Palindrome Linked List -判断链表是否为回文序列
- 判断是否为回文
- 判断是否为回文
- 判断是否为回文
- 判断是否为回文
- 判断是否为回文
- 判断是否为回文
- Leetcode-234. Palindrome Linked List(判断链表是否回文)
- LeetCode 234. Palindrome Linked List判断链表是否回文
- LeetCode234_PalindromeLinkedList (判断是否为回文链表) Java题解
- 利用栈判断链表是否为回文
- 判断一个链表是否为回文结构
- 判断一个链表是否为回文结构(java实现)
- 判断一个链表是否为回文结构
- 如何解决CRITICAL glance [-] AttributeError: 'NoneType' object has no attribute 'drivername'
- 队列阻塞及描述
- hdu 5282 Senior's String 两次dp
- 指针和内存分配一个最基本理解
- Android实习02:"摇一摇"功能的实现
- leetcode系列(16)判断链表是否为回文
- 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- Android中加载的图片自动适应屏幕(新手)
- Android Fragment的标准写法
- 微信PC版为什么这么设计?
- 欢迎使用CSDN-markdown编辑器
- 类中static并没有那么简单
- 10003 - Cutting Sticks(DP)
- iOS UIImageView 圆角