【链表】leetcode_707_设计链表
c++
构造虚拟头结点
基本操作,注意边界。
struct LinkedNode{
int val;
LinkedNode* next;
LinkedNode(int x): val(x), next(nullptr){};
};
class MyLinkedList {
public:
friend struct LinkedNode;
/** Initialize your data structure here. */
MyLinkedList() {
p = new LinkedNode(0);
m_length = 0;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if (index<0 || index>m_length-1) return -1;
LinkedNode *tmp = p;
for (int j=0; j<=index; j++){
tmp = tmp->next;
}
return tmp->val;
}
// int get(int index) {
// if (index<0 || index>(m_length-1)){
// return -1;
// }
// int i=0;
// LinkedNode *cur=p;
// while(i<=index)
// {
// cur=cur->next;
// i++;
// }
// return cur->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) {
LinkedNode *cur = new LinkedNode(val);
cur->next = p->next;
p->next = cur;
m_length++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
LinkedNode *cur = new LinkedNode(val);
LinkedNode* end = p;
while (end->next){
end=end->next;
}
end->next = cur;
m_length++;
}
/** 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) {
LinkedNode *cur = new LinkedNode(val);
LinkedNode *before = p;
if (index>m_length || index<0) return;
for (int j =0; j<index; j++){
before = before->next;
}
cur->next = before->next;
before->next = cur;
m_length++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index<0 || index>m_length-1) return;
LinkedNode *before = p;
int j = 0;
while(j<index ){
before = before->next;
j++;
}
if (before->next->next==nullptr){
LinkedNode *tmp = before->next;
before->next = nullptr;
delete tmp;
m_length--;
}else{
LinkedNode *tmp = before->next;
before->next = before->next->next;
delete tmp;
m_length--;
}
}
private:
int m_length;
LinkedNode* p;
};
1620

被折叠的 条评论
为什么被折叠?



