新聞中心
Given a linked list, swap every two adjacent nodes and return its head.

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:國(guó)際域名空間、虛擬空間、營(yíng)銷(xiāo)軟件、網(wǎng)站建設(shè)、定海網(wǎng)站維護(hù)、網(wǎng)站推廣。
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
給定鏈表,每?jī)蓚€(gè)節(jié)點(diǎn)為一組,交換相應(yīng)節(jié)點(diǎn)。
解題:
1)如果鏈表為空或者鏈表只有一個(gè)節(jié)點(diǎn),則直接返回鏈表
2)取出相鄰兩節(jié)點(diǎn)A,B。并把list往后移動(dòng)兩次。
3)其實(shí)交換兩節(jié)點(diǎn)實(shí)質(zhì)就是交換兩節(jié)點(diǎn)的val值,故進(jìn)行值交換即可。
說(shuō)明:
1)list != NULL檢查是防止出現(xiàn)list為NULL時(shí),此時(shí)執(zhí)行l(wèi)ist->next會(huì)出現(xiàn)段錯(cuò)誤。
2)list->next != NULL是說(shuō)明交換的兩個(gè)節(jié)點(diǎn)存在。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head)
{
if ( head == NULL || head->next == NULL )
{
return head;
}
struct ListNode *list = head;
struct ListNode *swapA = NULL;
struct ListNode *swapB = NULL;
while ( list != NULL && list->next != NULL )
{
swapA = list;
swapB = list->next;
list = list->next->next;
int val = 0;
val = swapA->val;
swapA->val = swapB->val;
swapB->val = val;
}
return head;
}
當(dāng)前名稱(chēng):[LeetCode]24.SwapNodesinPairs
網(wǎng)頁(yè)鏈接:http://www.dlmjj.cn/article/ihggoj.html


咨詢
建站咨詢
