203. 移除链表元素
删除链表中等于给定值 val 的所有节点。
Example 1
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
code 1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
//if(head == NULL) return NULL;
struct ListNode *p = NULL;
struct ListNode *q = head;
while(q != NULL)
{
if(q->val == val)
{
if(q == head)
{
head = head->next;
q = head;
}
else
{
p->next = q->next;
q = p->next;
}
}
else
{
p = q;
q = q->next;
}
}
return head;
}
code 2
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
if(head == NULL) return NULL;
struct ListNode *p=NULL;
struct ListNode *q=head;
while(q->next != NULL)
{
if(q->next->val == val)
{
p = q->next;
q->next = p->next;
free(p);
}
else
q = q->next;
}
if(head->val == val)
{
p = head->next;
free(head);
head = p;
}
return head;
}