2023年9月9日 星期六

[1721] Swapping Nodes in a Linked List

逋的廖喔~竟然一次PASS,只是要跑兩次迴圈XD
先把first version 貼上來~再來寫one pass 版

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapNodes(struct ListNode* head, int k){
if (head == NULL || head->next == NULL)
return head;
struct ListNode* ptr=head;
int count=0;
struct ListNode *fromhead, *fromend;
while (ptr!=NULL)
{
count++;
if (count==k)
fromhead = ptr;
ptr = ptr->next;
}
int target = count-k +1;
count = 0;
ptr=head;
while (ptr!=NULL)
{
count++;
if (count==target)
{
fromend = ptr;
break;
}
ptr = ptr->next;
}
int tmp = fromhead->val;
fromhead->val = fromend->val;
fromend->val = tmp;
return head;
}

啊啊啊~再次感受到自己的進步真的是很感動QQ 
但是漂亮的ONE PASS 解法我大概還是不會自己想到就是了 XD

struct ListNode* swapNodes(struct ListNode* head, int k){
if (head == NULL || head->next == NULL)
return head;
struct ListNode* ptr=head;
int count=0;
struct ListNode *fromhead, *fromend;
while (ptr!=NULL)
{
count++;
if (count==k)
{
fromhead = ptr;
fromend = head;
}
ptr = ptr->next;
if (count>k)
fromend = fromend->next;
}
int tmp = fromhead->val;
fromhead->val = fromend->val;
fromend->val = tmp;
return head;
}

沒有留言:

張貼留言