这题比较简单
重点就是使用了虚头节点后 可以节省许多的工作,如何写一些while循环比较简单。 找链表最后一个元素最简单的方法
while (cur->next != nullptr)
cur = cur->next;
class MyLinkedList {
public:
// 定义节点
struct ListNode
{
int val;
ListNode *next;
ListNode(int v) : val(v), next(nullptr) {}
};
// MyLinkedList的构造函数
MyLinkedList() {
size = 0;
dummy = new ListNode(0);
}
int get(int index) {
if (index < 0 || index >= size) // 索引无效 返回-1
return -1;
ListNode *cur = dummy->next;
// 获取第index个节点的值
while (index--)
{
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode *n = new ListNode(val);
n->next = dummy->next;
dummy->next = n;
++size; //一定记得加size
}
void addAtTail(int val) {
ListNode *n = new ListNode(val);
ListNode *cur = dummy;
// 找当前最后一个节点
while (cur->next != nullptr)
cur = cur->next;
cur->next = n;
++size;
}
void addAtIndex(int index, int val) {
if (index > size) return;
else if (index < 0) index = 0;
ListNode *cur = dummy;
ListNode *n = new ListNode(val);
// 寻找index前一个节点
while(index-- != 0)
{
cur = cur->next;
}
n->next = cur->next;
cur->next = n;
++size;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= size)
return;
ListNode *cur = dummy;
while(index-- != 0)
cur = cur->next;
ListNode *de = cur->next;
cur->next = de->next;
delete de;
--size;
}
private:
int size;
ListNode *dummy;
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/