LeetCode
来源:互联网 发布:苹果8没网络 编辑:程序博客网 时间:2024/06/08 00:07
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?
判断一个链表是不是回文,我的方法是把前一半链表翻转,然后再同时扫描,判断值是否相等。时间复杂度O(n),至于空间复杂度,我觉得翻转一个链表的空间复杂度是O(n),不是O(1)
/** * 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) return true; ListNode* tail = head; int len = 0; while (tail) { len++; tail = tail->next; } tail = NULL; ListNode* cur = NULL; int len2 = len / 2; while(len2--) { tail = head->next; head->next = cur; cur = head; head = tail; } if (len % 2) head = head->next; bool flag = false; while (head) { if (head->val == cur->val) { head = head->next; cur = cur->next; continue; } flag = true; break; } if (flag) return false; return true; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Linux权限
- web安全色
- Babelfish POJ
- 单变量线性回归中的梯度下降法求解代价函数的最小值
- Linux下安装Mongodb
- LeetCode
- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
- Oracle 12c 使用普通用户的步骤
- PAT甲级 1037 -- 没有注释
- 【CDOJ1059】秋实大哥与小朋友
- MYSQL当权限更改生效时
- Android -- Service官方文档简译
- QT 为按钮添加事件
- PAT甲级 1038 -- 没有注释