mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
@ -275,7 +275,50 @@ var reverseList = function(head) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Ruby:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
# 双指针
|
||||||
|
# Definition for singly-linked list.
|
||||||
|
# class ListNode
|
||||||
|
# attr_accessor :val, :next
|
||||||
|
# def initialize(val = 0, _next = nil)
|
||||||
|
# @val = val
|
||||||
|
# @next = _next
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
def reverse_list(head)
|
||||||
|
# return nil if head.nil? # 循环判断条件亦能起到相同作用因此不必单独判断
|
||||||
|
cur, per = head, nil
|
||||||
|
until cur.nil?
|
||||||
|
tem = cur.next
|
||||||
|
cur.next = per
|
||||||
|
per = cur
|
||||||
|
cur = tem
|
||||||
|
end
|
||||||
|
per
|
||||||
|
end
|
||||||
|
|
||||||
|
# 递归
|
||||||
|
# Definition for singly-linked list.
|
||||||
|
# class ListNode
|
||||||
|
# attr_accessor :val, :next
|
||||||
|
# def initialize(val = 0, _next = nil)
|
||||||
|
# @val = val
|
||||||
|
# @next = _next
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
def reverse_list(head)
|
||||||
|
reverse(nil, head)
|
||||||
|
end
|
||||||
|
|
||||||
|
def reverse(pre, cur)
|
||||||
|
return pre if cur.nil?
|
||||||
|
tem = cur.next
|
||||||
|
cur.next = pre
|
||||||
|
reverse(cur, tem) # 通过递归实现双指针法中的更新操作
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user