问题描述
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
思路分析
删除链表中与指定值相同的所有节点,简单的链表删除。
并不简单啊,首先要考虑head为NULL的情况,直接返回head;然后考虑开始连续几个基点都需要删除,用一个while来解决,head = head->next,有可能删空,所以在while后有一个判断。然后就能确定head在要返回的链表上,接下来常规操作,next的val是指定的就跳过它,循环整个链表。
代码
/**
* 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) {
while (head != NULL && head->val == val){
head = head->next;
}
if (head == NULL)
return head;
ListNode* p = head;
while (p->next != NULL){
if (p->next->val == val)
p->next = p->next->next;
else
p = p->next;
}
return head;
}
};
时间复杂度:
O(logn)
空间复杂度:
O(1)
反思
简单的链表题不简单,对于链表还是不够熟悉,需要静下心来好好划分这几种情况的。