20.4.22 移除链表元素 简单 203
时间复杂度O(n),空间复杂度O(1)
题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解题思路
- 删除结点就要在该结点的前面留一个指针,但是特殊情况就是当head的结点需要删除时,前面不能加指针;
- 所以总共分两种情况,第一种,删除head,第二种,删除除了head的结点。
代码思路
- 如果head结点要删除,则不断后移head指针,第一次while的结束条件是,head为空或者head结点不需要删除;
- 分别给两个指针赋值;
- 第二个循环就是第二个情况,结束条件时curr指针为空
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *front,*curr;
while(head!=NULL&&head->val==val){
head=head->next;
}
if(head!=NULL){
front=head;
curr=head->next;
}
else return head;
while(curr!=NULL){
if(curr->val==val){
front->next=curr->next;
curr=front->next;
}
else{
front=curr;
curr=curr->next;
}
}
return head;
}
};