zoukankan      html  css  js  c++  java
  • leetcode 234 回文链表 Palindrome Linked List

    要求用O(n)时间,和O(1)空间,因此思路是用本身链表进行判断,既然考虑回文,本方法思想是先遍历一次求链表长度,然后翻转前半部分链表;然后同时对前半部分链表和后半部分链表遍历,来判断对应节点的值是否对应相等,时间复杂度应该为O(2n),空间复杂度O(3);基本符合要求,但是运行时间还是有点长;

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool isPalindrome(ListNode* head) {
    12         if(head==NULL||head->next==NULL) return true;
    13         ListNode* cur,*pre;
    14         cur=head;
    15         int length=0;
    16         while(cur!=NULL){
    17             length+=1;
    18             cur=cur->next;
    19         }
    20         cur=head->next;pre=head;head->next=NULL;
    21         for(int i=1;i<(length+1)/2;i++){
    22                 ListNode* temp;
    23                 temp=cur->next;
    24                 cur->next=pre;
    25                 pre=cur;
    26                 cur=temp;
    27         }
    28         if(length%2==1) pre=pre->next;
    29         while(cur!=NULL){
    30             if(cur->val==pre->val){
    31                 cur=cur->next;pre=pre->next;
    32             }
    33             else return false;
    34         }
    35         return true;
    36     }
    37 };

  • 相关阅读:
    P2043 质因子分解
    CODE[VS] 3164 质因数分解
    借过
    CODE[VS] 1165 字符串的展开 || P1098 字符串的展开
    CODE[VS] 1144 守望者的逃离 || P1095 守望者的逃离
    CODE[VS] 2914 吹空调
    AC日记
    AC日记
    山科日记—回文
    山科日记—编写函数myFloor和myCeil(编程题)
  • 原文地址:https://www.cnblogs.com/joelwang/p/10447280.html
Copyright © 2011-2022 走看看