题目:
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分析:
初步判断可以发现有两种情况的删除,一种是第一个节点的删除,一种是中间节点的删除,为了保持统一,让算法保持简洁的设计,所以手动添加一个新的节点辅助作为第一个节点代码:
ListNode* removeElements(ListNode* head, int val) {
ListNode *newNode = new ListNode(-1);
newNode->next = head;
ListNode *currentNode = head;
ListNode *previousNode = newNode;
while (currentNode != NULL) {
if (currentNode->val == val) {
currentNode = currentNode->next;
previousNode->next = currentNode;
} else {
previousNode = currentNode;
currentNode = currentNode->next;
}
}
return newNode->next;
}