234. Palindrome Linked List leetcode list

Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
ollow up:
Could you do it in O(n) time and O(1) space?

//本题可以采用暴力解决测办法,这需要使用一个额外的栈,则时间空间复杂度均为O(n)
    //本处采用的思路为:首先找到链表的中间点,然后将中间点后的半段链表进行逆转,然后将前半段单链表以及后半段单链表从头到尾进行遍历,
    //进行素的比较
    bool isPalindrome(ListNode* head) {
        if(NULL == head || NULL == head->next)
        {
            return true;
        }

        ListNode* middle = getListMid(head);
        ListNode* headTwo = reverseList(middle);

        while(head && headTwo)
        {
            if(head->val != headTwo->val)
            {
                return false;
            }

            head = head->next;
            headTwo = headTwo->next;
        }

        return true;
    }

    ListNode* getListMid(ListNode* head)
    {
        if(NULL == head || NULL == head->next)
        {
            return head;
        }

        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* preslow = head;
        while(fast)
        {
            fast = fast->next;
            if(fast)
            {
                fast = fast->next;
                preslow = slow;
                slow = slow->next;
            }
        }

        preslow->next = NULL;
        return slow;
    }

    ListNode* reverseList(ListNode* head)
    {
        if(NULL == head || NULL == head->next)
        {
            return head;
        }

        ListNode* finalList = NULL;
        while(head)
        {
            ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
            temp->val = head->val;
            temp->next = finalList;
            finalList = temp;
            head = head->next;
        }

        return finalList;
    }

其他解决办法:http://www.bkjia.com/ASPjc/1031678.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值