补第三天的内容
问题:对于指针的初始化不是很了解
解决:指针初始化的三种方式
int num = 5;
int *ptr = # // 将num的地址赋给ptr指针
int *ptr = new int; // 动态分配一个整型变量的内存,并将地址赋给ptr指针
int num1 = 5;
int num2 = 10;
int *ptr1 = &num1;
int *ptr2 = ptr1; // 将ptr1指针的值赋给ptr2指针
lc203移除列表元素
自己的代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy_head = new ListNode(0); // 初始化虚拟头结点
ListNode *pre = dummy_head; // pre指向虚拟头结点
// ListNode *cur = dummy_head->next; // cur指向原来的头结点
while (pre->next != nullptr) { // 当pre指向的元素下一个元素不为空时循环
if (pre->next->val == val) {
// pre->next = cur->next; // 将pre指向节点的指针域指向cur的下一个节点,删除cur
ListNode * cur = pre->next;
pre->next = cur->next;
delete cur;
} else {
pre = pre->next;
}
}
head = dummy_head->next;
delete dummy_head;
return head;
}
};
问题:不太会调试,输出答案为[],找不明白错误在哪儿
照着抄的代码:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *pre = dummyHead;
while (pre->next != nullptr) {
if (pre->next->val == val) {
ListNode *cur = pre->next;
pre->next = cur->next;
delete cur;
}
else {
pre = pre->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
第4天
lc24
代码:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *cur = dummyHead;
while (cur->next != nullptr && cur->next->next != nullptr) {
ListNode *temp = cur->next;
ListNode *temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
lc19删除倒数第N个节点
代码:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *slow = dummyHead;
ListNode *fast = dummyHead;
while(n-- && fast != NULL) {
fast = fast->next;
}
fast = fast->next;
while(fast != NULL) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};