12-206. Reverse Linked List

题目描述:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

代码实现:

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def reverseList(self, head: ListNode) -> ListNode:
 9         prev = None
10         while head:
11             curr = head
12             head = head.next
13             curr.next = prev
14             prev = curr
15         return prev

 

posted @ 2019-05-31 23:39  mingyu02  阅读(143)  评论(0编辑  收藏  举报