题目
Remove Linked List Elements
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
标签
Linked List
难度
简单
分析
题目意思是给定一个单链表和一个value,删除链表里和value相同的节点,返回新的链表。我的做法是先找到要返回链表的头结点,然后遍历链表,如果遇到和value不相同的节点,则保存节点,否则跳过。
C代码实现
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode * p;
struct ListNode * q;
struct ListNode * ret;
if(!head)
return NULL;
p = head;
while(p && (p->val == val)) // find the head of the return list
{
p = p->next;
}
if(!p)
return NULL;
q = p;
ret = q; // keep the first element of the return list
p = p->next;
while(p)
{
if(p->val != val) // if val is not equal the p->val, save it to the return list
{
q->next = p;
q = p;
}
p = p->next;
}
q->next =NULL;
return ret;
}