Algorithm Leet Code Easy [Swift] Reverse Linked List

[Swift] Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Image

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Image

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

풀러가기

문제 이해

코드

func reverseList(_ head: ListNode?) -> ListNode? {
  var current = head
  var previous: ListNode?
  var following = head

  while current != nil { 
   following = following?.next
   current?.next = previous
   previous = current
   current = following
  }

  return previous
}

풀이

-

다른 분의 멋진 코드

-

잘 배웠습니다.

-

댓글남기기