(c语言)力扣之回文链表

回文链表
请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
//递归 以及反转链表   ,边界性往往是最难考虑的

bool isPalindrome(struct ListNode* head){
    if(head == NULL || head -> next == NULL)
        return true; //当长度为0和1的时候要特殊考虑
   struct ListNode *fast = head, *slow = head;
   while(fast && fast -> next){
       fast = fast -> next -> next;
        if(!fast )
            break;
        slow = slow -> next;
   }
  
//快慢指针找中间节点
   struct ListNode *temp, * prev = slow , *mid = slow;
    slow = slow -> next;
   while(slow -> next){
   temp = slow -> next;
   slow -> next = prev;
   prev = slow;
   slow = temp;
   }
   slow ->next = prev;
    //反转后半截链表
   fast = head;
   while( slow != mid){
       if(slow -> val != fast -> val){
           return false;
       }
       fast = fast -> next;
       slow = slow -> next;
   }
   return true;
}

你可能感兴趣的:(链表,leetcode,算法)