题目

判断一个链表是否是回文的。

/**
 * 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) {
        
        int len = getLength(head);
        
        if(len==1||len==0)
            return true;
        
        int x = len%2==0?len/2:len/2+1;
        
        ListNode* start = head;
        ListNode* end =reverseNode(getNode(head,x));
        
        while(end!=NULL)
        {
            if(start->val!=end->val)
                return false;
            start=start->next;
            end=end->next;
        }
        
        return true;
        
    }
    ListNode* reverseNode(ListNode* root)
    {
        ListNode* term =root->next;
        root->next = NULL;
        while(term!=NULL)
        {
            ListNode* temp = term->next;
            term->next = root;
            root=term;
            term = temp;
        }
        return root;
    }
    
    ListNode* getNode(ListNode* root,int pos)
    {
        int x=0;

        while(root!=NULL)
        {
            if(x==pos)
                return root;
            x++;
            root=root->next;
        }
        return root;
    }
    
    int getLength(ListNode* root)
    {
        int ans=0;
        while(root!=NULL)
        {
            ans++;
            root=root->next;
        }
        
        return ans;
    }
};

相关文章:

  • 2021-10-25
  • 2022-01-05
  • 2022-01-13
  • 2022-12-23
  • 2021-05-24
  • 2022-01-10
  • 2021-06-01
猜你喜欢
  • 2021-12-26
  • 2021-04-21
  • 2021-06-03
  • 2021-06-02
  • 2021-07-23
  • 2021-08-12
相关资源
相似解决方案