Leetcode206(代码随想录:反转链表)
C++代码:
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) {} };
在链表结构体中定义构造函数可以在初始化结点时直接为结点赋值,避免产生空指针异常。
双指针方法:
/**
* 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; //必须初始化为空
ListNode *cur = head;
while(cur)
{
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
递归方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// ListNode *pre = nullptr;
return reverse(nullptr, head);
}
ListNode *reverse(ListNode *pre, ListNode *cur){
if(cur == nullptr)
return pre;
ListNode *temp = cur->next;
cur->next = pre;
return reverse(cur, temp);
}
};
Python代码:
1. python求数组nums长度:
len(nums)
2. python取整:
middle = (left + right) // 2
3. python移除数组nums中的元素val:
nums.remove(val)
4.(1)python升序排序,列表本身修改:
nums.sort()
(2)python升序排序,返回新列表:
sorted(nums)
5.(1)列表地址相同:result = nums
(2)创建列表副本:result = nums[:]
6.(1)float('inf'):正无穷大
(2)float('-inf'):负无穷大
7. 建立二维列表的方法:result = [[0] * n for _ in range(n)]
8. Python中的空类型:None
9. 在类中:
(1)成员函数互相调用使用:self.函数名
(2)调用其他类的函数使用:类名.函数名
Python定义链表类:
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next
双指针方法:
# 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]:
cur = head
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
递归方法:
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.reverse(head, None)
def reverse(self, cur: ListNode, pre: ListNode) -> ListNode:
if cur == None:
return pre
temp = cur.next
cur.next = pre
return self.reverse(temp, cur)