1, 题目

反转一个单链表。

示例:

  1. 输入: 1->2->3->4->5->NULL
  2. 输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2, 算法

  1. object Solution {
  2. def reverseList(head: ListNode): ListNode = {
  3. val result = new ListNode()
  4. var current = head
  5. while (current != null) {
  6. val t = current
  7. current = current.next
  8. t.next = null
  9. t.next = result.next
  10. result.next = t
  11. }
  12. val x = result.next
  13. result.next = null
  14. x
  15. }
  16. }
  1. class Solution:
  2. def reverseList(self, head: ListNode) -> ListNode:
  3. result = ListNode()
  4. while head:
  5. t = head
  6. head = head.next
  7. t.next = None
  8. t.next = result.next
  9. result.next = t
  10. head = result.next
  11. result.next = None
  12. return head