203.移除链表元素
题目本身很简单,主要就是是否使用虚拟头结点dummyhead
虚拟头结点,我们用虚拟头结点省去对链表头结点的特判
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//设立虚拟头结点
ListNode* dummyNode = new ListNode(0, head);
//遍历链表,跳过目标元素
ListNode* cur = dummyNode;
while (cur != nullptr && cur->next != nullptr)
{
if (cur->next->val == val)
{
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else
{
cur = cur->next;
}
}
return dummyNode->next;
}
};
707.设计链表
这道题是对我提升最大的,因为它帮助我真正从零设计了一个类,很好地提高了代码能力。
具体内容都是很基础的链表常用方法,不在赘述,由于赶时间我只做了单链表的设计,之后可以尝试双向链表
1.单链表
class MyLinkedList {
public:
//单链表
struct ListNode {
int val;
ListNode* next;
//结点构造函数
ListNode(int val) : val(val), next(nullptr) {}
};
private:
int _size;
ListNode* _dummyNode;
public:
//构造函数
MyLinkedList() {
_dummyNode = new ListNode(0);
_size = 0;
}
int get(int index) {
//超限直接返回-1
if (index > (_size - 1) || index < 0) return -1;
//遍历到指定下标
ListNode* p = _dummyNode->next;
while (index--) p = p->next;
return p->val;
}
//头插
void addAtHead(int val) {
ListNode* tmp = new ListNode(val);
tmp->next = _dummyNode->next;
_dummyNode->next = tmp;
_size++;
}
//尾插
void addAtTail(int val) {
ListNode* tmp = new ListNode(val);
ListNode* p = _dummyNode;
while (p->next != nullptr) p = p->next;
p->next = tmp;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) return;
ListNode* tmp = new ListNode(val);
//p找到对应下标的前一个结点
ListNode* p = _dummyNode;
while (index--) p = p->next;
tmp->next = p->next;
p->next = tmp;
_size++;
}
void deleteAtIndex(int index) {
if (index > _size - 1 || index < 0) return;
//p找到对应下标的前一个结点
ListNode* p = _dummyNode;
for (int i = 0; i < index; i++) p = p->next;
ListNode* tmp = p->next;
p->next = p->next->next;
delete tmp;
_size--;
}
};
206.反转链表
方法1:头插法(需要额外内存空间)
ListNode* reverseList(ListNode* head) {
//不考虑空间地情况下,我们可以头插法
ListNode* p = head;
ListNode* dummyNode = new ListNode();
while (p != nullptr)
{
ListNode* tmp = new ListNode(p->val);
tmp->next = dummyNode->next;
dummyNode->next = tmp;
tmp = p;
p = p->next;
delete tmp;
}
p = dummyNode->next;
delete dummyNode;
return p;
}
方法2:就地翻转(迭代)
ListNode* reverseList(ListNode* head) {
if (head == nullptr) return head;
//就地翻转
ListNode* cur = head;
ListNode* pre = nullptr;
ListNode* tmp;
while (cur != nullptr && cur->next != nullptr)
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
方法3:就地反转(递归)
ListNode* reverseList(ListNode* head) {
//递归翻转
if (head == nullptr || head->next == nullptr) return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}