万事开头难
1.使用现有链表头结点head
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *temp;
//当头结点存在并且头结点的值等于val
while(head && head->val == val){
temp = head;
//更新头结点,并删除原来的头结点
head = head -> next;
free(temp);
}
struct ListNode *cur = head;
//cur指向头结点
while(cur && (temp = cur ->next)){
if(temp->val == val){
//将cur->next指向cur->next->next并删除cur->next
cur->next = temp -> next;
free(temp);
}
//若cur->next不等于val,则cur后移
else cur = cur -> next;
}
return head;
}
2.使用虚拟头结点
要想使用虚拟头结点,需要先创建结点,使用malloc
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
typedef struct ListNode ListNode;
ListNode *shead;
shead = (ListNode*)malloc(sizeof(ListNode));
//虚拟头结点,要先创建一个结点
shead->next = head;
ListNode *cur = shead;
//cur指向虚拟头结点
while(cur->next != NULL){
if(cur->next->val == val){
ListNode *temp = cur->next;
cur->next = temp->next;
free(temp);
}
else cur = cur->next;
}
head = shead->next;
free(shead);
return head;
}