迭代

【leetcode题解】使用迭代或递归的方式反向链表 - 图1

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * struct ListNode *next;
  6. * };
  7. */
  8. struct ListNode* reverseList(struct ListNode* head){
  9. if(head == NULL || head->next == NULL) return head;
  10. struct ListNode * p = reverseList(head->next);
  11. head->next->next = head;
  12. head->next = NULL;
  13. return p;
  14. }

回归

  • 对于下一个或者自身为NULL的节点执行返回,此返回值为逆转后的头部
  • 对于中间节点:使自己的下一个节点指向自己;使自己指向的节点为空;返回头部值;

代码

  1. if(head == NULL || head->next == NULL) return head;
  2. struct ListNode * p = reverseList(head->next);
  3. head->next->next = head;
  4. head->next = NULL;
  5. return p;