题目描述.PNG
#include <iostream>
#include <vector>
#include <stack>
#include <list>
#include <queue>
using namespace std;
class MyLinkedList
{
public:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
MyLinkedList()
{
_size = 0;
dummy = new ListNode(0);
}
int get(int index)
{
if (index > (_size - 1) || index < 0)
return -1;
ListNode *cur = dummy->next;
while (index--)
{
cur = cur->next;
}
return cur->val;
}
void addHead(int val)
{
ListNode *newNode = new ListNode(val);
newNode->next = dummy->next;
dummy->next = newNode;
_size++;
return;
}
void addTail(int val)
{
ListNode *newNode = new ListNode(val);
ListNode *cur = dummy;
while (cur->next)
{
cur = cur->next;
}
cur->next = newNode;
_size++;
return;
}
void addIndex(int index, int val)
{
if (index > _size)
return;
ListNode *newNode = new ListNode(val);
ListNode *cur = dummy;
while (index--)
{
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
_size++;
return;
}
void deleteIndex(int index, int val)
{
if (index > _size)
return;
ListNode *cur = dummy;
while (index--)
{
cur = cur->next;
}
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
_size--;
return;
}
void printList()
{
ListNode *cur = dummy->next;
while (cur->next)
{
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
return;
}
private:
int _size;
ListNode *dummy;
};
网友评论