代码随想录算法训练营第三天 | 链表理论基础 | 707.设计链表
-
要求太多,代码量太大,实在难以完成
-
在以前听说,好的程序员,可以在短时生成大量的代码,本题只方法才只有6个,根本不算多
-
每天手敲代码量太少,才是问题
-
#include <iostream>class MyLinkedList { private:struct Node {int val;Node* next;Node(int v): val(v), next(nullptr) {}};Node* visualHead;int len; public:MyLinkedList() {visualHead = new Node {0};len = 0;}int get(int index) {if (len == 0 || index < 0 || index > len - 1) return -1;auto *p = visualHead->next;for ( ; index--; p = p->next);return p->val;}void addAtHead(int val) {Node *new_node = new Node {val};auto* old_next = visualHead->next;visualHead->next = new_node;new_node->next = old_next;++len;}void addAtTail(int val) {Node *new_node = new Node {val};auto* p = visualHead;for (; p->next != nullptr; p = p->next);p->next = new_node;++len;}void addAtIndex(int index, int val) {if (index < 0 || index > len) return;Node *new_node = new Node {val};auto *p = visualHead;for ( ; index--; p = p->next);new_node->next = p->next;p->next = new_node;++len;}void deleteAtIndex(int index) {if (index >= len || index < 0) return;auto* p = visualHead;for (; index--; p = p->next);auto* delNode = p->next;p->next = p->next->next;delete delNode;delNode = nullptr;--len;} };int main() {MyLinkedList mll {};mll.addAtHead(3);mll.addAtTail(5);mll.addAtIndex(2, 8);mll.addAtIndex(2, 7);std::cout << mll.get(1) << std::endl;std::cout << mll.get(0) << std::endl;std::cout << mll.get(2) << std::endl;std::cout << mll.get(3) << std::endl;return 0; }
-
学习到的是在链中遍历时,使用
index--
是可以省略多定义变量的,但老师也说了,写成--index
会死循环,是什么道理? -
汇总