2022年12月1日 星期四

[2095] Delete the Middle Node of a Linked List

其實我不知道為什麼我想要精簡卻寫出好長一串.........
好像先算出總長,來找出next 要跑幾次比較好嗎XD
不會因為想要一次塞進去結果反而多了好多判斷式><
霸特Q心慌亂~這題就先降子吧(擦汗)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteMiddle(struct ListNode* head){
struct ListNode *pre, *one, *two;
one=head;
if (one!=NULL)
two=head->next;
pre=NULL;
while(two != NULL && two->next !=NULL)
{
pre=one;
one=one->next;
two=two->next;
if (two->next !=NULL)
{
two=two->next;
if(two->next==NULL)
{
pre=one;
one=one->next;
break;
}
}
}
if (pre==NULL)
{
if (one->next !=NULL)
{
one->next=NULL;
return head;
}
else
return NULL;
}

pre->next=one->next;
one->next=NULL;
free(one);
return head;
}

沒有留言:

張貼留言