您的位置:首页 > 财经 > 金融 > LeetCode707 设计链表

LeetCode707 设计链表

2025/1/8 3:27:04 来源:https://blog.csdn.net/daishabby2486/article/details/140682659  浏览:    关键词: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;
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com