常规法
记录前一个指针,当前指针,后一个指针,遍历链表,改变指针的指向。
//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)
{
ListNode *pre=nullptr;
while(head)
{
ListNode *nex=head->next;
head->next=pre;
pre=head;
head=nex;
}
return pre;
}
};
#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre=None
while head:
nex=head.next
head.next=pre
pre=head
head=nex
return pre
递归法
对于每一个元素的下一个的下一个要指向自己,自己再指向空,递归进去得到头指针。
//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||!head->next) return head;
ListNode * ne=reverseList(head->next);
head->next->next=head;
head->next=nullptr;
return ne;
}
};
#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
new=self.reverseList(head.next)
head.next.next=head;
head.next=None;
return new