题目:206. 反转链表

题目:206. 反转链表

反转一个单链表。

方式一(迭代)

 public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode curr = head;
        ListNode prev = null;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        return prev;
    }

方式二(递归)

  public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode res = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }
上一篇:在Python中,令values=[0,1,2];values[1]=values,为何结果是[0,[...],2]?


下一篇:CUDA学习笔记(三)——共享内存