struct SinglyLinkList {
int val;
SinglyLinkList* next;
SinglyLinkList() {
this->val = -1;
this->next = nullptr;
}
};
class MyLinkedList {
public:
SinglyLinkList* head, * newNode, * nowNode;
int linkListLen;
/** Initialize your data structure here. */
MyLinkedList() {
head = new SinglyLinkList();
linkListLen = 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 >= linkListLen) //处理无效index
return -1;
int rec = 0;
nowNode = head;
//找到index对应的节点
while (rec != index) {
rec++;
nowNode = nowNode->next;
}
return nowNode->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) {
linkListLen++;
if (head->val == -1) {
head->val = val;
return;
}
newNode = new SinglyLinkList();
newNode->val = val;
newNode->next = head;
head = newNode;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
linkListLen++;
if (head->val == -1) {
head->val = val;
return;
}
newNode = new SinglyLinkList();
newNode->val = val;
nowNode = head;
//找到为节点
while (nowNode->next != nullptr) {
nowNode = nowNode->next;
}
nowNode->next = newNode;
}
void addAtIndex(int index, int val) {
//根据题意分四种情况
if (index > linkListLen)
return;
else if (index == linkListLen)
addAtTail(val);
else if (index <= 0)
addAtHead(val);
else {
SinglyLinkList *preNode;
int rec = 0;
preNode = nowNode = head;
while (rec != index) {
rec++;
preNode = nowNode;
nowNode = nowNode->next;
}
newNode = new SinglyLinkList();
newNode->val = val;
preNode->next = newNode;
newNode->next = nowNode;
linkListLen++;
}
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index < 0 || index >= linkListLen)
return;
linkListLen--;
int rec = 0;
SinglyLinkList* preNode;
preNode = nowNode = head;
while (rec != index) {
rec++;
preNode = nowNode;
nowNode = nowNode->next;
}
if (preNode == nowNode) {
if (head->next == nullptr) {
head->val = -1;
}
else {
head = head->next;
}
}
else {
preNode->next = nowNode->next;
}
}
};
LeetCode设计链表(C++)
最新推荐文章于 2024-08-15 05:02:54 发布