707 设计单链表
第一次完成這樣的設計,一路磕磕碰碰,遇到了許多問題,最后終于一一解決了。感恩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;}};?
總結
- 上一篇: 排骨的功效与作用、禁忌和食用方法
- 下一篇: leetcode 二进制求和 addBi