链表-移除链表元素
题目链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: ListNode* removeElements(ListNode* head, int val) { while(head->val == val && head != NULL){ ListNode* tmp = head; head = head->next; delete tmp; } ListNode* cur = head; while(cur->next != NULL && cur != NULL){ if(cur->next->val == val){ ListNode* tmp = cur->next; cur->next = cur->next->next; delete tmp; } else{ cur = cur->next; } }
return head; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| struct ListNode* removeElements(struct ListNode* head, int val){ struct ListNode* myhead = malloc(sizeof(struct ListNode)); myhead->next = head; struct ListNode* temp = myhead; while (temp->next != NULL) { if (temp->next->val == val) { temp->next = temp->next->next; } else { temp = temp->next; } } return myhead->next; }
|
1 2 3 4 5 6 7 8 9 10
| class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: myhead = ListNode(next = head) cur = myhead while(cur.next != None): if(cur.next.val == val): cur.next = cur.next.next else: cur = cur.next return myhead.next
|
python可真是简单了,c/c++需要自己释放删掉的元素。