707. 设计链表 - 力扣(LeetCode)
需要注意每次删除或者添加的时候,记得更新头结点。
class MyLinkedList {
struct Node{
int val;
Node *next;
Node(int x) : val(x), next(NULL) {}
};
public:
Node * dummy, *head = NULL;
/** Initialize your data structure here. */
MyLinkedList() : dummy(new Node(-1)), head(NULL){
dummy->next = head;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
auto node = dummy;
for(int i = 0; i <= index; ++i){
if(node) node = node->next;
else return -1;
}
return node == NULL ? -1 : node->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 addAtHead(int val) {
auto node = new Node(val);
node->next = head;
dummy->next = node;
head = node;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
auto node = new Node(val);
auto p = dummy;
while(p->next) p = p->next;
p->next = node;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
void addAtIndex(int index, int val) {
auto p = dummy;
for(int i = 0; i < index; ++i){
if(p) p = p->next;
else return;
}
auto node = new Node(val);
node->next = p->next;
p->next = node;
head = dummy->next;//此处可能需要更新head
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
auto p = dummy;
for(int i = 0; i < index; ++i){
if(p) p = p->next;
else return;
}
auto tmp = p->next;
if(tmp == NULL) return;
p->next = tmp->next;
head = dummy->next;//可能会删除首部的节点,所以需要更新
}
};
优化的话可以维护一个size,或者使用双向链表的话效率会好很多。