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

示例 1:

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

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

问题:

1、当链表的个数是奇数时,为了使slow往后移动一个单位,需要用到此判断,为什么fast的下一个结点为NULL设为条件是错误的呢?

  1. // if (fast->next == NULL)
  2. if (fast != NULL) {
  3. slow = slow->next;
  4. }
  5. // Line 39: Char 17: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

image.png
第 39 行:字符 17:运行时错误:“struct ListNode”类型的空指针内的成员访问 [solution.c]

2、
image.png上面的if判断不能写上去,因为它是不等于NULL就移位

代码:

1.快慢指针方法

////

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * struct ListNode *next;
  6. * };
  7. */
  8. struct ListNode * reverNode(struct ListNode * head) {
  9. if(head->next == NULL) {
  10. return head;
  11. }
  12. // 使用迭代的方法会效率高一点
  13. struct ListNode * pre = NULL;
  14. struct ListNode * cur = head;
  15. struct ListNode * nxt = head;
  16. while(cur != NULL) {
  17. nxt = cur->next;
  18. cur->next = pre;
  19. pre = cur;
  20. cur = nxt;
  21. }
  22. return pre;
  23. }
  24. bool isPalindrome(struct ListNode* head){
  25. // 如果head是空或者下一个指针是空的话,直接返回true
  26. if (head == NULL || head->next == NULL) {
  27. return true;
  28. }
  29. // 定义快慢指针
  30. struct ListNode * slow = head;
  31. struct ListNode * fast = head;
  32. // 让其到对应的位置,考虑奇数条件
  33. while(fast != NULL && fast->next != NULL) {
  34. slow = slow->next;
  35. fast = fast->next->next;
  36. // if (fast->next == NULL)
  37. }
  38. if (fast != NULL) {
  39. slow = slow->next;
  40. }
  41. // 应该是有fast指向NULL的可能,所以不能这样判断
  42. // if (fast->next == NULL) {
  43. // slow = slow->next;
  44. // }
  45. // 对slow指针后的结点进行翻转
  46. struct ListNode * right = reverNode(slow);
  47. struct ListNode * left = head;
  48. // 两边同时进行迭代对比
  49. while (right != NULL) {
  50. if(right->val != left->val) {
  51. return false;
  52. }
  53. right = right->next;
  54. left = left->next;
  55. }
  56. return true;
  57. }