2024年7月31日 星期三

[1171] Remove Zero Sum Consecutive Nodes from Linked List

好像是不需要用一個array 出來存linked list 的value (嗎)
一邊遍歷linked list 可以一邊算presum (嗎)
假設都已經要先跑一次求出總node數了 (嗎)
總之Orz 先這樣吧給你一個TBD XD


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeZeroSumSublists(struct ListNode* head) {
int *arr = calloc (1000, sizeof(int));
struct ListNode *ptr = head;
int count=0;
while (ptr != NULL)
{
arr[count++]= ptr->val;
ptr = ptr->next;
}

int *presum = calloc (count, sizeof(int));
struct ListNode **nodes = calloc (count, sizeof(struct ListNode*));
for (int i=0;i<count; i++)
nodes[i]= calloc (1, sizeof(struct ListNode));
ptr = head;
int recount=0;
presum[0]= arr[0];
while (ptr != NULL)
{
nodes[recount++] = ptr;
if (recount<count)
presum[recount] = presum[recount-1]+arr[recount];
ptr = ptr->next;
}

for (int i=0; i<count; i++)
{
if (presum[i]==0)
head = nodes[i]->next;

for (int j=count-1; j>i; j--)
{
if (presum[i]== presum[j])
{
nodes[i]->next = nodes[j]->next;
break;
}
}
}
return head;
}


沒有留言:

張貼留言