https://leetcode.com/problems/swap-nodes-in-pairs/
一個連結串列,交換2個相鄰的節點並返回首節點。
先用p1、p2紀錄首節點跟下一個節點,進行交換後temp用來記錄下一個要交換的節點,直到條件符合時跳出迴圈。
struct ListNode* swapPairs(struct ListNode* head) {
if (head == NULL || head -> next == NULL )
return head;
struct ListNode *p1 = head;
struct ListNode *p2 = head -> next;
struct ListNode *result = p2;
struct ListNode *temp = NULL ;
while (p1 != NULL && p2 != NULL )
{
p1 -> next = p2 -> next;
p2 -> next = p1;
if (temp != NULL )
temp -> next = p2;
temp = p1;
if (p1 -> next != NULL && p1 -> next -> next != NULL )
{
p1 = p1 -> next;
p2 = p1 -> next;
}
else
break ;
}
return result;
}
var swapPairs = function(head) {
if (head == null || head.next == null )
return head;
var p1 = new ListNode(0);
var p2 = new ListNode(0);
var result = new ListNode(0);
var temp = new ListNode(0);
p1 = head;
p2 = head.next;
result = p2;
temp = null;
while (p1 != null && p2 != null )
{
p1.next = p2.next;
p2.next = p1;
if (temp != null )
temp.next = p2;
temp = p1;
if (p1.next != null && p1.next.next != null )
{
p1 = p1.next;
p2 = p1.next;
}
else
break ;
}
return result;
};
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
Accept yourself and experience the perfection in imperfections in life
接受自己,體會生命裡不完美中的完美