Leetcode203. 刪除連結串列中的元素_C語言
題目:https://leetcode-cn.com/problems/remove-linked-list-elements/description/
題解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//LinkList;
struct ListNode* removeElements(struct ListNode* head, int val) {
typedef struct ListNode *Linklist;
Linklist prehead,del,cur,pre;
prehead=(Linklist)malloc(sizeof(struct ListNode));
prehead->next=head;
pre=prehead;//前驅指標
cur=head;//現在的
while(cur)//不需要判斷cur的下一個是否為NULL,因為cur==NULL時迴圈終止
{
if(cur->val==val)
{
del=cur;
pre->next=cur->next;
cur=cur->next;
free(del);
}
else
{
pre=cur;
cur=cur->next;
}
}
return prehead->next;
}