leetcode 234. Palindrome Linked List

来源:互联网 发布:mysql utf8 utf8mb4 编辑:程序博客网 时间:2024/06/18 07:40

原题:

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

Follow up:
Could you do it in O(n) time and O(1) space?

题目分析:

主要的难点在于时间和空间的要求

代码如下:


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */bool isPalindrome(struct ListNode* head) {    struct ListNode* fast;    struct ListNode* slow;    fast=head;    slow=head;    if(head==NULL||head->next==NULL)        return true;    while(fast&&fast->next)    {        slow=slow->next;        fast=fast->next->next;    }    struct ListNode* otherhead;    otherhead=(struct ListNode*)malloc(sizeof(struct ListNode));    otherhead->next=NULL;    struct ListNode* p1;    struct ListNode* p2;    if(!fast)    {        p1=slow;    }    else    {        p1=slow->next;    }    while(p1)    {        p2=otherhead->next;        otherhead->next=p1;        p1=p1->next;        otherhead->next->next=p2;    }    while(otherhead->next)    {        if(otherhead->next->val!=head->val)        {            return false;        }        otherhead=otherhead->next;        head=head->next;    }    return true;}

这个主要学到的地方是快慢指针求中位数,这种方法还是比较简便的。

另外就是,链表反转。

其实不难,但今天是周五。感觉写起来程序兴趣索然。