题目要求:
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?
这里先只做一个迭代法,利用两个指针来实现,基本思想就是用两个指针一起往后遍历来实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre=None
cur=head
while cur:
nextnode=cur.next
cur.next=pre
pre=cur
cur=nextnode
return pre