1.使用双指针法进行链表的反转
在操作时,需要注意的是,先对pre进行操作,再执行cur的覆盖,否则pre无法走到先前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)
{
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur)
{
ListNode* tmp;
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
//最终cur指向了nullptr,而pre指向了先前链表的尾部,也即翻转之后链表1的头结点
return pre;
}
};
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: Optional[ListNode]
:rtype: Optional[ListNode]
"""
cur = head
pre = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur = head;
struct ListNode* pre = NULL;
while(cur)
{
struct ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
2.利用递归进行链表的反转
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)
{
return reverse(head,nullptr);
}
ListNode* reverse(ListNode* cur,ListNode* pre)
{
ListNode* tmp;
if(cur == nullptr) return pre;
tmp = cur->next;
cur->next = pre;
return reverse(tmp,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 reverse(self,cur,pre):
if cur == None:
return pre
tmp = cur.next
cur.next = pre
return self.reverse(tmp,cur)
def reverseList(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
cur = head
pre = None
return self.reverse(head,None)
C:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* cur,struct ListNode* pre)
{
if(cur == NULL)
return pre;
struct ListNode* tmp = cur->next;
cur->next = pre;
return reverse(tmp,cur);
}
struct ListNode* reverseList(struct ListNode* head)
{
return reverse(head,NULL);
}