题解 | #判断一个链表是否为回文结构#

判断一个链表是否为回文结构

http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
        // write code here
        ListNode * newhead = new ListNode(0),*head2 = NULL;
        newhead->next = NULL;
        ListNode *slow = head,*fast = head->next;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        //偶数个
        head2 = slow->next;
        while(head && head != head2){
            ListNode *temp = newhead->next;
            newhead->next = head;
            ListNode* cur = head->next;
            head->next = temp;
            head = cur;
        }
        if(fast == NULL)
            newhead = newhead->next;
        while(head2){
            if(newhead->next->val != head2->val)
                return false;
            head2 = head2->next;
            newhead = newhead->next;
        }
        return true;
    }
};
全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
感性的干饭人在线蹲牛友:🐮 应该是在嘉定这边叭,禾赛大楼挺好看的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务