设置一个虚拟头节点,虚拟头节点的next为head,然后声明一个head的前置节点curr,初始值为node
遍历链表,如果值等于val,则curr的next指向下一个节点,否则curr后移。无论是否等于val,head都后移,直到head为空。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* removeElements(ListNode* head, int val) { 14 ListNode* node = new ListNode(-1); 15 node->next = head; 16 ListNode* pre = node; 17 while(head!=NULL){ 18 if(head->val == val){ 19 pre->next = head->next; 20 }else{ 21 pre = head; 22 } 23 head = head->next; 24 } 25 return node->next; 26 } 27 };
链表增删察。需要有个size
1 class MyLinkedList { 2 public: 3 struct ListNode{ 4 int val; 5 ListNode* next; 6 ListNode(int val,ListNode* next):val(val),next(next){ 7 } 8 }; 9 ListNode* head; 10 int size; 11 MyLinkedList() { 12 head = new ListNode(-1,nullptr); 13 size = 0; 14 } 15 16 int get(int index) { 17 if(index >= size) return -1; 18 ListNode* curr = head->next; 19 while(index--){ 20 curr = curr->next; 21 } 22 return curr->val; 23 } 24 25 void addAtHead(int val) { 26 ListNode* node = new ListNode(val,nullptr); 27 node->next = head->next; 28 head->next = node; 29 size++; 30 } 31 32 void addAtTail(int val) { 33 ListNode* node = new ListNode(val,nullptr); 34 ListNode* curr = head; 35 while(curr->next != nullptr){ 36 curr = curr->next; 37 } 38 curr->next = node; 39 size++; 40 } 41 42 void addAtIndex(int index, int val) { 43 if(index > size) return; 44 ListNode* node = new ListNode(val,nullptr); 45 ListNode* curr = head; 46 while(index--){ 47 curr = curr->next; 48 } 49 node->next = curr->next; 50 curr->next = node; 51 size++; 52 } 53 54 void deleteAtIndex(int index) { 55 if(index >= size) return; 56 ListNode* curr = head; 57 while(index--){ 58 curr = curr->next; 59 } 60 curr->next = curr->next->next; 61 size--; 62 } 63 }; 64 65 /** 66 * Your MyLinkedList object will be instantiated and called as such: 67 * MyLinkedList* obj = new MyLinkedList(); 68 * int param_1 = obj->get(index); 69 * obj->addAtHead(val); 70 * obj->addAtTail(val); 71 * obj->addAtIndex(index,val); 72 * obj->deleteAtIndex(index); 73 */
没啥好说的,递归
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverseList(ListNode* head) { 14 if(head == nullptr || head->next == nullptr) return head; 15 ListNode* node = reverseList(head->next); 16 head->next->next = head; 17 head->next = nullptr; 18 return node; 19 } 20 };
浙公网安备 33010602011771号