LeetCode 707. Design Linked List
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList class:
MyLinkedList() Initializes the MyLinkedList object.
int get(int index) Get the value of the indexth node in the `linked list. If the index is invalid, return -1.
void addAtHead(int val) `Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
void addAtTail(int val) Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]
method
取节点和删节点的index不能到最后一个元素的下一个_size
增加节点可以到最后一个元素的下一个_size
不管是索引、插入还是删除index的元素,指针都是从头结点开始,通过循环while(index--)走到index-1的位置,再对next进行操作
class MyLinkedList {
public:
ListNode *_dummy = new ListNode(0);
int _size = 0;
MyLinkedList() {}
int get(int index) { // 等于也不行,因为是空
if (index >= _size || index < 0) return -1;
ListNode *cur = _dummy;
while (index--) {
cur = cur->next; // index-1
}
return cur->next->val; // 返回next的值
}
void addAtHead(int val) {
ListNode *node = new ListNode(val);
node->next = _dummy->next;
_dummy->next = node;
_size++;
}
void addAtTail(int val) {
ListNode *cur = _dummy;
while (cur->next) cur = cur->next; // 找到最后一个元素
ListNode *node = new ListNode(val);
cur->next = node;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) return; // 等于可以,因为要新建元素
ListNode *cur = _dummy;
while (index--) cur = cur->next; // index-1
ListNode *node = new ListNode(val);
node->next = cur->next; // 插入到next位置
cur->next = node;
_size++;
}
void deleteAtIndex(int index) { // 等于也不行,因为是空
if (index >= _size || index < 0) return;
ListNode *cur = _dummy;
while (index--) cur = cur->next; // index-1
cur->next = cur->next->next; // 删除next
_size--;
}
};