Question
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
My Answer
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* cur = head;
struct ListNode* pre = NULL;
while(cur){
if(cur->val == val){
if(pre){
pre->next = cur->next;
free(cur);
cur = pre->next;
}else{ //the value of the first node is equal to the given val.
head = cur->next;
//free(cur);
cur = head;
}
}else{
pre = cur;
cur = cur->next;
}
}
return head;
}
the complete code
#include <stdio.h>
#include <stdlib.h>
//definition for the singly-linked list.
struct ListNode{
int val;
struct ListNode *next;
};
void build(struct ListNode* head, int* nums, int numsSize){
struct ListNode *p, *q;
p = head;
for(int i=0; i<numsSize; ++i){
q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->next = NULL;
q->val = nums[i];
p->next = q;
p = q;
}
}
void print(const struct ListNode* head){
struct ListNode* p = head->next;
while(p != NULL){
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* cur = head;
struct ListNode* pre = NULL;
while(cur){
if(cur->val == val){
if(pre){
pre->next = cur->next;
free(cur);
cur = pre->next;
}else{ //the value of the first node is equal to the given val.
head = cur->next;
//free(cur);
cur = head;
}
}else{
pre = cur;
cur = cur->next;
}
}
return head;
}
int main()
{
struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode));
L->next = NULL;
L->val = -1;
int A[] = {1,1};
//int A[] = {};
build(L, A, 2);
print(L);
struct ListNode* head = removeElements(L, 1);
print(head);
return 0;
}