1. 程式人生 > 其它 >c基礎語法02

c基礎語法02

做題思路:

  1,就考察了連結串列的基礎操作,題目要求什麼就照做就好了

 1 class MyLinkedList {
 2 public:
 3     struct LinkedList {   //甚至還先需要自己整一個連結串列的結構體,平時做題做慣了這裡會忘先弄結構體了
 4         int val;
 5         LinkedList* next;
 6         LinkedList(int val) : val(val), next(nullptr) {}
 7     };
 8     MyLinkedList() {
 9 
10     }
11     LinkedList* fakeNode = new
LinkedList(0); //經典虛擬頭節點,不知道為什麼如果把這行放到上面的建構函式裡面就識別不到,說未定義,真奇怪 12 int size = 0; //為了檢測 index 是否合法 13 int get(int index) { 14 if (index > (size - 1) || index < 0)return -1; 15 LinkedList* cur = fakeNode; 16 while (index--) { 17 cur = cur->next; 18 }
19 return cur->next->val; 20 } 21 22 void addAtHead(int val) { 23 LinkedList* cur = new LinkedList(val); 24 cur->next = fakeNode->next; 25 fakeNode->next = cur; 26 size++; 27 } 28 29 void addAtTail(int val) { 30 LinkedList* cur = fakeNode;
31 while (cur->next != nullptr) { 32 cur = cur->next; 33 } 34 LinkedList* newNode = new LinkedList(val); 35 cur->next = newNode; 36 size++; 37 } 38 39 void addAtIndex(int index, int val) { 40 if (index > size)return ; 41 LinkedList* cur = fakeNode; 42 while (index--) { 43 cur = cur->next; 44 } 45 LinkedList* newNode = new LinkedList(val); 46 newNode->next = cur->next; 47 cur->next = newNode; 48 size++; 49 } 50 51 void deleteAtIndex(int index) { 52 if (index >= size || index < 0)return ; 53 LinkedList* cur = fakeNode; 54 while (index--) { 55 cur = cur->next; 56 } 57 LinkedList* temp = cur->next; 58 cur->next = cur->next->next; 59 delete temp; 60 size--; 61 } 62 }; 63 64 /** 65 * Your MyLinkedList object will be instantiated and called as such: 66 * MyLinkedList* obj = new MyLinkedList(); 67 * int param_1 = obj->get(index); 68 * obj->addAtHead(val); 69 * obj->addAtTail(val); 70 * obj->addAtIndex(index,val); 71 * obj->deleteAtIndex(index); 72 */