題目
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
範例
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
struct ListNode* swapPairs(struct ListNode* head){
if(!head||!head->next)return head;
if(!head->next->next){
struct ListNode *ptr=head;
head=ptr->next;
ptr->next->next=ptr;
ptr->next=NULL;
return head;
}
struct ListNode *ptr=head,*ptr2=head->next->next;
head=ptr->next;
ptr->next=ptr2;
head->next=ptr;
while(ptr2->next){
ptr2=ptr2->next;
ptr->next->next=ptr2->next;
ptr2->next=ptr->next;
ptr->next=ptr2;
ptr=ptr2->next;
if(ptr->next){
ptr2=ptr->next;
}else{
return head;
}
}
return head;
}
思路: 假設 a->b->c->d 其中b,c為要swap的偶數對 則宣告兩指標 ptr ptr2指向a&c
a->b->c->d
^ ^
ptr ptr2
要做事情有3
a->b->
^ d
ptr c->
^
ptr2
ptr
a->
b->d
c->
ptr2
ptr
a->c->b->d
ptr2
至此bc完成swap且ad正確接上
最後ptr與ptr2位置往前循環做1-3步(ptr到b,ptr2到d的下一個)
如果d沒有下一個直接回傳
Leetcode 1. Two Sum (C/Python3)
Oct 25, 2023K-th Symbol in Grammar
Oct 25, 2023You are given a 0-indexed sorted array of integers nums.
Sep 16, 2023Rectangle ( MAC split screen / resize window shortcut ) ( MAC 分屏 / 調整視窗大小 快捷鍵 ) windows 上 win + 左右調整視窗分屏在MAC沒有預設鍵位 開源免費軟體 Rectangle 能做到這件事情 官網直接下載安裝 https://rectangleapp.com
Dec 13, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up