赞
踩
- #include <iostream>
- #include <vector>
- using namespace std;
-
- class MyLinkedList {
- public:
- struct ListNode {
- int val;
- ListNode* next;
- ListNode(int x) : val(x), next(nullptr) {}
- };
-
- MyLinkedList() {
- size = 0;
- dummyhead = new ListNode(0);
- }
-
- int get(int index) {
- if (index < 0 || index >= size) {
- return -1;
- }
- ListNode *cur = dummyhead->next;
- for (int i = 0; i < index; i++) {
- cur = cur->next;
- }
- return cur->val;
- }
-
- void addAtHead(int val) {
- addAtIndex(0, val);
- }
-
- void addAtTail(int val) {
- addAtIndex(size, val);
- }
-
- void addAtIndex(int index, int val) {
- if (index > size) {
- return;
- }
- index = max(0, index);
- size++;
- ListNode *pred = dummyhead;
- for (int i = 0; i < index; i++) {
- pred = pred->next;
- }
- ListNode *toAdd = new ListNode(val);
- toAdd->next = pred->next;
- pred->next = toAdd;
- }
-
- void deleteAtIndex(int index) {
- if (index < 0 || index >= size) {
- return;
- }
- size--;
- ListNode *pred = dummyhead;
- for (int i = 0; i < index; i++) {
- pred = pred->next;
- }
- ListNode *toDelete = pred->next;
- pred->next = pred->next->next;
- delete toDelete;
- }
-
- private:
- int size;
- ListNode *dummyhead;
- };
-
-
- int main() {
- MyLinkedList linkedList; // 创建链表对象
-
- // 使用 addAtTail 方法添加元素
- linkedList.addAtTail(1);
- linkedList.addAtTail(2);
- linkedList.addAtTail(3);
- linkedList.addAtTail(4);
- linkedList.addAtTail(5);
- linkedList.addAtTail(6);
-
- // 打印链表来检查元素
- for (int i = 0; i < 6; i++) {
- cout << linkedList.get(i) << ' ';
-
- }
- cout <<endl;
-
- // 测试其他功能,例如删除和在头部添加
- linkedList.deleteAtIndex(3); // 删除索引3的元素,即数字4
- linkedList.addAtHead(0); // 在头部添加0
-
- for (int i = 0; i < 6; i++) {
- cout << linkedList.get(i) << ' ';
-
- }
- cout <<endl;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。