https://leetcode.cn/problems/reverse-linked-list/
代码实现 java
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
{
return head;
}
ListNode cur=reverseList(head.next);
head.next.next=head;
head.next=null;
return cur;
}
}
c++
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
{
return head;
}
ListNode *cur=reverseList(head->next);
head->next->next=head;
head->next=nullptr;
return cur;
}
};
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(head==None or head.next==None):
return head;
cur=self.reverseList(head.next)
head.next.next=head
head.next=None
return cur



