Reverse Linked List

描述

Reverse a singly linked list.

分析

用三个指针 tail,p,q,紧紧相邻,不断前进,每次将p.next指向tail,将q.next指向p

解法1 迭代

  1. // Reverse Linked List
  2. // Time Complexity: O(n), Space Complexity: O(1)
  3. public class Solution {
  4. public ListNode reverseList(ListNode head) {
  5. if (head == null || head.next == null) return head;
  6. ListNode tail = null;
  7. ListNode p = head;
  8. ListNode q = p.next;
  9. while (q != null) {
  10. ListNode old = q.next;
  11. p.next = tail;
  12. q.next = p;
  13. tail = p;
  14. p = q;
  15. q = old;
  16. }
  17. return p;
  18. }
  19. }

解法2 递归

  1. // Reverse Linked List
  2. // Time Complexity: O(n), Space Complexity: O(n)
  3. public class Solution {
  4. public ListNode reverseList(ListNode head) {
  5. if (head == null || head.next == null) return head;
  6. ListNode tail = head.next;
  7. head.next = null;
  8. ListNode newHead = reverseList(tail);
  9. tail.next = head;
  10. return newHead;
  11. }
  12. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/reverse-linked-list.html