2024年2月2日 星期五

[2074] Reverse Nodes in Even Length Groups

這個算是group reverse linked list 系列吧
雖然對於一次要反轉幾個有點卡住
想說要先算起來還是怎樣的,但先弄起來反而就知道要把reverse 塞在哪兒了吧。

整理過後的code 長這樣,我懶得把它弄的更漂亮了XD 先降紫~~~~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

struct ListNode* reverseEvenLengthGroups(struct ListNode* head) {
struct ListNode *ptr = head;
int check = 0;
while (ptr != NULL)
{
ptr = ptr->next;
check++;
}
int move;
ptr=head;
struct ListNode *ptrPre= NULL;
struct ListNode *pre, *curr, *next;

for (int i=1; check >0; i++)
{
if (check - i < 0) //last group
{
if (check %2==0)
{
pre = NULL;
curr = ptr;
while (curr != NULL)
{
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
ptrPre->next = pre;
}
break;
}
check-= i;
move = i;
if (i%2==0)
{
pre = NULL;
curr = ptr;

while (move > 0)
{
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
move --;
}
ptrPre->next = pre;
ptr->next = curr;
ptrPre=ptr;
ptr = ptr->next;
}
else // move ptr
{
while (move>0)
{
move--;
ptrPre= ptr;
ptr = ptr->next;
}
}
}
return head;
}

下面是一點都不重要的,算有幾個要reverse,跟最後一個要不要reserve ,的code  XD
struct ListNode* reverseEvenLengthGroups(struct ListNode* head) {
struct ListNode *ptr = head;
int count = 0;
while (ptr != NULL)
{
ptr = ptr->next;
count++;
}
int check = count;
int evenCount=0;
bool last = false;
ptr=head;
for (int i=1; check >0; i++)
{
if (check - i < 0)
{
if (check %2==0)
{
last= true;
evenCount++;
}
break;
}
check-= i;
int move = i;
if (i%2==0)
evenCount++;
}

// printf("%d %d \n", count, evenCount);
return head;
}

沒有留言:

張貼留言