请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
问题:
1、当链表的个数是奇数时,为了使slow往后移动一个单位,需要用到此判断,为什么fast的下一个结点为NULL设为条件是错误的呢?
// if (fast->next == NULL)if (fast != NULL) {slow = slow->next;}// Line 39: Char 17: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

第 39 行:字符 17:运行时错误:“struct ListNode”类型的空指针内的成员访问 [solution.c]
2、
上面的if判断不能写上去,因为它是不等于NULL就移位
代码:
1.快慢指针方法
////
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode * reverNode(struct ListNode * head) {if(head->next == NULL) {return head;}// 使用迭代的方法会效率高一点struct ListNode * pre = NULL;struct ListNode * cur = head;struct ListNode * nxt = head;while(cur != NULL) {nxt = cur->next;cur->next = pre;pre = cur;cur = nxt;}return pre;}bool isPalindrome(struct ListNode* head){// 如果head是空或者下一个指针是空的话,直接返回trueif (head == NULL || head->next == NULL) {return true;}// 定义快慢指针struct ListNode * slow = head;struct ListNode * fast = head;// 让其到对应的位置,考虑奇数条件while(fast != NULL && fast->next != NULL) {slow = slow->next;fast = fast->next->next;// if (fast->next == NULL)}if (fast != NULL) {slow = slow->next;}// 应该是有fast指向NULL的可能,所以不能这样判断// if (fast->next == NULL) {// slow = slow->next;// }// 对slow指针后的结点进行翻转struct ListNode * right = reverNode(slow);struct ListNode * left = head;// 两边同时进行迭代对比while (right != NULL) {if(right->val != left->val) {return false;}right = right->next;left = left->next;}return true;}
