• leetcode 234. 回文链表


    2023.9.5

            本题先将链表的节点值移到数组中,再用双指针去判断该数组是否为回文的即可。 代码如下:

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. bool isPalindrome(ListNode* head) {
    14. vector<int> nums;
    15. while(head)
    16. {
    17. nums.push_back(head->val);
    18. head = head->next;
    19. }
    20. int left = 0;
    21. int right = nums.size()-1;
    22. while(left <= right)
    23. {
    24. if(nums[left] != nums[right]) return false;
    25. left++;
    26. right--;
    27. }
    28. return true;
    29. }
    30. };

    2023.11.10

            二刷,思路还是先将链表的值放入数组中,判断数组是否回文就简单多了。 java代码如下:

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public boolean isPalindrome(ListNode head) {
    13. List nums = new ArrayList<>();
    14. nums.add(head.val);
    15. while(head.next != null){
    16. head = head.next;
    17. nums.add(head.val);
    18. }
    19. for(int i=0; i
    20. if(nums.get(i) != nums.get(nums.size()-i-1)) return false;
    21. }
    22. return true;
    23. }
    24. }

  • 相关阅读:
    MFC中不同编码格式内容的写入
    计算机毕业设计Python+Django的个人博客系统(源码+系统+mysql数据库+Lw文档)
    Redis事务
    axios学习
    Alibaba Druid整合
    github(不是git啊)操作记录(踩坑)
    14.3.6 创建组合索引
    Mybatis动态SQL踩坑记
    新点面试题
    SpringBoot--WEB技术基础
  • 原文地址:https://blog.csdn.net/m0_61028090/article/details/132686575