Leetcode 206 Reverse Linked List

Reverse链表。使用三个指针head,a,b,最后head会指向最后一个node,故直接返回head。

x -> x -> x -> x =>  x <- x   x -> x   =>   x <- x x -> x  =>      x <- x <- x  x

h     a      b          a.next = head            h  a     b      a.next = head

def reverse(head)
  return if not head 
    a = head.next
    head.next = nil
  while a
    b = a.next
    a.next = head
    head = a
    a = b
  end
  head
end

 

posted @ 2015-06-17 17:55  lilixu  阅读(288)  评论(0编辑  收藏  举报