zoukankan      html  css  js  c++  java
  • 234 判断是否为回文链表

    1、回文链表定义

    前后对称 

    2、思路

    快慢指针slow/fast

    • 找到中间结点
    • 把后半部分输入到栈中,然后从链表第一个元素和出栈元素比较,是否相等,如果不等 就返回false
    • 特殊情况别忘了考虑空链表和只含有一个结点的链表!!
    • stack<int>q;定义栈(先进后出)
    • q.top();求出栈顶元素
    • q.push(整形元素);q.pop()(删除顶部元素)
    • q.empty()判断栈是否为空!!

    3、真的是改了不少bug,一定要主要指针要指的有意义

    4、代码

     
     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         ListNode *slow,*fast,*p;//p为了保留slow的位置
    13         fast=head;
    14         slow=head;
    15         //if(head==NULL) return true;//第一次没考虑这种情况
    16         //if(head!=NULL&&head->next==NULL) return true;//这种情况也没考虑
    17         p=head;
    18         if(head!=NULL&&head->next!=NULL){
    19         while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL){
    20             slow=slow->next;
    21             p=p->next;
    22             fast=fast->next->next;
    23         }
    24         if(fast->next!=NULL) {
    25             slow=slow->next;
    26             p=p->next; }
    27         else{
    28             slow=slow->next;
    29         }
    30             while(slow!=NULL){
    31             q.push(slow->val);
    32             slow=slow->next;
    33         }
    34             while(head!=p&&!q.empty()){
    35             if(head->val==q.top()){
    36                 head=head->next;
    37                 q.pop();
    38             }
    39             else{
    40                 break;//跳出循环执行循环后面的语句,continue是结束本次循环,执行下一次循环
    41             }
    42         }
    43         bool a;
    44         a=q.empty();
    45         return a;
    46         }
    47    else
    48       {return true;}
    49     }
    50 private:
    51     stack<int>q;
    52     
    53 };

    5、时间复杂度还行,空间复杂度不好!!

  • 相关阅读:
    MSClass (Class Of Marquee Scroll通用不间断滚动JS封装类)
    IE和FF下javascript获取网页宽高及窗口大小
    JSON View – JSON格式化查看工具
    查询功能所属的菜单
    会计科目API CCID
    应付的帐龄分析SQL
    采购到入库所经历的表
    金额大小写转换(2)
    oracle行列转换总结
    金额大小写转换(1)
  • 原文地址:https://www.cnblogs.com/hehesunshine/p/11636001.html
Copyright © 2011-2022 走看看