题目链接
https://leetcode.cn/problems/reverse-linked-list/
代码实现
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
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++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
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