LeetCode707 设计链表
前言
题目: 707. 设计链表
文档: 代码随想录——设计链表
编程语言: C++
解题状态: 代码功底不够,只能写个大概
思路
主要考察对链表结构的熟悉程度,对链表的增删改查,比较考验代码功底以及对链表的掌握。本题中的一些边界条件也要注意。
代码
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
MyLinkedList() {
_dummyHead = new ListNode(0);
_size = 0;
}
int get(int index) {
if (index > (_size - 1) || index < 0) {
return -1;
}
ListNode* cur = _dummyHead -> next;
while (index--) {
cur = cur -> next;
}
return cur -> val;
}
void addAtHead(int val) {
ListNode* newNode = new ListNode(val);
newNode -> next = _dummyHead -> next;
_dummyHead -> next = newNode;
_size++;
}
void addAtTail(int val) {
ListNode* newNode = new ListNode(val);
ListNode* cur = _dummyHead;
while (cur -> next != nullptr) {
cur = cur -> next;
}
cur -> next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size) {
return;
}
ListNode* newNode = new ListNode(val);
ListNode* cur = _dummyHead;
while (index--) {
cur = cur -> next;
}
newNode -> next = cur -> next;
cur -> next = newNode;
_size++;
}
void deleteAtIndex(int index) {
if (index >= _size || index < 0) {
return;
}
ListNode* cur = _dummyHead;
while (index--) {
cur = cur -> next;
}
ListNode* tmp = cur -> next;
cur -> next = cur -> next -> next;
delete tmp;
_size--;
}
void printLinkedList() {
ListNode* cur = _dummyHead;
while (cur -> next != nullptr) {
cout << cur -> next -> val << " ";
cur = cur -> next;
}
cout << endl;
}
private:
int _size;
ListNode* _dummyHead;
};
原文地址:https://blog.csdn.net/daishabby2486/article/details/140682659
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!