2023年8月15日 星期二

[203] Remove Linked List Elements

結果筆試考這題
完全炸 XD
奇怪XD 我還以為我只剩linked list 的sorting 沒寫R  XD

原本我的版本長這樣: 
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* p, *pre;
p=head;
pre=NULL;
while(p!=NULL)
{
if (p->val != val)
{
pre = p;
p = p->next;
continue;
}

if (p==head)
{
head = p->next;
p->next = NULL;
free(p);
p=head;
}
else
{
pre->next = p->next;
p->next=NULL;
free(p);
p=pre->next;
}
}
return head;
}

然後發現~大家寫的都沒有free 耶XD  咦不用free 嗎 XD
然後如果head 一直指到要拿掉的node , 它就無痛向後就好了 Orz
所以可以很漂亮的寫成: 

struct ListNode* removeElements(struct ListNode* head, int val){
if (head==NULL)
return head;

while (head != NULL && head->val == val)
head=head->next;

struct ListNode* p1, *pre;
p1=head;
pre=NULL;
while(p1 !=NULL)
{
if (p1->val== val)
{
pre->next = p1->next;
p1=p1->next;
}
else
{
pre = p1;
p1=p1->next;
}
}
return head;
}

沒有留言:

張貼留言