反转单向链表(JAVA)

在微博看到,有人说8个应届毕业生没有人写出o(1)空间复杂度,o(n)时间复杂度的反转单向链表。

(不是我自己想的)

public void reverseList(ListNode head)
{
    ListNode newHead = null;
    while(head != null)
    {
        ListNode next = head.next;
        head.next = newHead;
        newHead = head;
        head = next;
    }
    return newHead;
}

 自己也想了很久,类似于:

  Head -> a ->b

  1.next = a

  Head ->null

  newHead =head

  Head =a

  2.next  = b

  a -> head

  newHead = a

  Head = b

  3.next = null

  b -> a

  newHead = b

  Head = null

  return newHead

  

posted @ 2016-02-26 17:15  dalu610  阅读(270)  评论(0编辑  收藏  举报