203. 移除链表元素

tech2022-08-30  119

题目:删除链表中等于给定值 val 的所有节点。

方法一:引入虚拟头结点dummy

函数代码:

class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) { return 0; } ListNode *dummy=new ListNode(0); dummy->next=head; ListNode *cur=dummy; //ListNode *pre=head; while(cur->next) { if(cur->next->val==val) { ListNode *deleteNode=cur->next; cur->next=deleteNode->next; delete deleteNode; } else { cur=cur->next; } } return dummy->next; } };

方法二:引入pre结点

class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) { return 0; } //防止头结点的值一直和目标值val重复,还要继续判断head是否为空 while(head) { if(head->val!=val) { break; } head=head->next; } ListNode *dummy=new ListNode(0); dummy->next=head; ListNode *cur=head; ListNode *pre=head; while(cur) { if(cur->val==val) { pre->next=cur->next; } else { pre=cur; } cur=cur->next; } return dummy->next; } };
最新回复(0)