zoukankan      html  css  js  c++  java
  • 234. Palindrome Linked List

    Given a singly linked list, determine if it is a palindrome.

    Example 1:

    Input: 1->2
    Output: false

    Example 2:

    Input: 1->2->2->1
    Output: true

    Follow up:
    Could you do it in O(n) time and O(1) space?
    判断单链表是不是回文串,首先写了一个反转链表函数reverseList,为了省时间在isPalindrome函数里面用双指针一快一慢让慢的走到中间的结点,然后只需要反转后面的一半结点,再跟前面的一半比较即可知道是不是回文串。

     1 struct ListNode* reverseList(struct ListNode* head) {
     2     if(!head)   return NULL;
     3     struct ListNode *prev=NULL,*next;
     4     while(head){
     5         next=head->next;
     6         head->next=prev;
     7         prev=head;
     8         head=next;
     9     }
    10     return prev;
    11 }
    12 bool isPalindrome(struct ListNode* head) {
    13     if(!head || !head->next) return true;
    14     
    15     struct ListNode *fast=head,*slow=head;
    16     //如果fast->next或者fast->next->next少一个判断都会导致慢指针走多一步导致结果错误
    17     while(fast && fast->next && fast->next->next){
    18         slow=slow->next;
    19         fast=fast->next->next;
    20     }
    21     struct ListNode *mid=reverseList(slow->next);
    22     slow->next=NULL;
    23     while(mid){
    24         if(mid->val!=head->val)
    25             return false;
    26         mid=mid->next;
    27         head=head->next;
    28     }
    29     return true;
    30 }
  • 相关阅读:
    ArcgisServerJS固件位置
    PrintTemplate说明
    地图打印仅地图4X
    地图打印4X
    IIS下设置跨域访问问题--Access-Control-Allow-Origin 站点跨域请求的问题
    javascript的 热点图怎么写
    Flex 加载shp
    Flex 加载dwg
    Flex 加载tiff
    Flex 加载 wmf,svg
  • 原文地址:https://www.cnblogs.com/real1587/p/9868078.html
Copyright © 2011-2022 走看看