记录力扣刷题第七题
本文包含C++两种解法以及Java和Python解法
题目描述如下
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
来源:LeetCode
思路:
记录每个节点的上一个节点和下一个节点,把指向下一个节点的指针指向上一个节点即可。代码实现也很简单,如下。
/**
* 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* nxt;
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur != nullptr) {
//先把当前节点的下一个节点存储起来,以防丢失
nxt = cur->next;
//将当前节点的next指针指向前一个节点。
cur->next = pre;
//将上一个节点与当前节点后移,注意这两句顺序不要写反
pre = cur;
cur = nxt;
}
return pre;
//每个节点的next指针指向都反转后,cur就为链表原本的尾节点,现在的头节点指向的空指针了
//因此要返回现在的头节点pre
};
注意一个细节:nxt在进行while循环之前不能被cur->next指向,因为cur可能为空,再使用其next指针的话就会导致执行出错。
接下来介绍一种稍微抽象一点的写法:递归写法
class Solution {
public:
ListNode* reverse(ListNode* pre, ListNode* cur) {
if(cur == nullptr) return pre;//递归终止条件
ListNode* nxt = cur->next;
cur->next = pre;
//进行递归
return reverse(cur, nxt);
//主函数调用递归函数进行递归
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
reverse(pre, cur);
}
};
其实看看代码理解理解就能看明白了,跟上一种方法原理是一样的,只不过是换成了递归的写法。
下面放上Java和Python的写法
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) {
ListNode nxt;
ListNode cur = head;
ListNode pre = null;
while(cur != null) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
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 Reverse(self, pre: ListNode, cur: ListNode) -> ListNode:
if cur == None:
return pre
nxt = cur.next
cur.next = pre
return self.Reverse(cur, nxt)
def reverseList(self, head: ListNode) -> ListNode:
cur = head
pre = None
return self.Reverse(pre, cur)