第一次完成这样的设计,一路磕磕碰碰,遇到了许多问题,最后终于一一解决了。感恩https://blog.csdn.net/lym940928/article/details/81276658
题目如下:
设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val
和 next
。val
是当前节点的值,next
是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev
以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
在链表类中实现这些功能:
- get(index):获取链表中第
index
个节点的值。如果索引无效,则返回-1
。 - addAtHead(val):在链表的第一个元素之前添加一个值为
val
的节点。插入后,新节点将成为链表的第一个节点。 - addAtTail(val):将值为
val
的节点追加到链表的最后一个元素。 - addAtIndex(index,val):在链表中的第
index
个节点之前添加值为val
的节点。如果index
等于链表的长度,则该节点将附加到链表的末尾。如果index
大于链表长度,则不会插入节点。 - deleteAtIndex(index):如果索引
index
有效,则删除链表中的第index
个节点。
下面是给的示例:
MyLinkedList linkedList = new MyLinkedList(); //创建链表 linkedList.addAtHead(1); //在头节点加入元素1,链表变为1->nullptr linkedList.addAtTail(3); //在尾节点加入元素3,链表变为1->3->nullptr linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3->nullptr linkedList.get(1); //返回2 linkedList.deleteAtIndex(1); //现在链表是1-> 3->nullptr linkedList.get(1); //返回3
class MyLinkedList {private: //声明一个链表的结构,单链表中有一个next的指针,一个val的值,还有一个声明节点的函数struct LinkNode{int val;LinkNode* next;LinkNode(int x):val(x), next(nullptr){}};int len; //代表链表的长度LinkNode *head;//头指针 LinkNode *tail;//尾指针public:/**Initialize your data structure here*/MyLinkedList(){head=new LinkNode(0); //初始化链表,头指针指向的元素为0,next为nullptrtail=head;len=0;}/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */int get(int index){LinkNode *pCur;pCur=head;if(index>len) return -1;elsefor(int i=0;i<=index;i++)pCur=pCur->next; return pCur->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){LinkNode *pCur=new LinkNode(val);pCur->next=head;head=pCur;len++; return;}/** Append a node of value val to the last element of the linked list. */void addAtTail(int val){LinkNode *pCur=new LinkNode(val);tail=head;if(tail->next!=nullptr)tail=tail->next; tail->next=pCur;pCur->next=nullptr;len++;return; }/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */void addAtIndex(int index,int val){if(index>len)return;LinkNode *pCur;LinkNode *add=new LinkNode(val);pCur=head;for(int i=0;i<index;i++)pCur=pCur->next;add->next=pCur->next;pCur->next=add;len++;return;}/** Delete the index-th node in the linked list, if the index is valid. */void deleteAtIndex(int index){if(index>=len) return;LinkNode *pCur;pCur=head;for(int i=0;i<index;i++)pCur=pCur->next;LinkNode *del = pCur->next;pCur->next = del->next;del->next = NULL;len--;return;}};