求:spa
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。code
你不能只是單純的改變節點內部的值,而是須要實際的進行節點交換。遞歸
示例:it
給定 , 你應該返回 1->2->3->42->1->4->3
解:io
遞歸解法:
/**
* 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* next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return
next;
}
循環解法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct
ListNode* swapPairs(
struct
ListNode* head){
struct
ListNode* pre = (
struct
ListNode*)malloc(
sizeof
(
struct
ListNode));
pre->next = head;
struct
ListNode* tmp = pre;
while
(tmp->next!=NULL && tmp->next->next!=NULL){
struct
ListNode* first = tmp->next;
struct
ListNode* second = first->next;
tmp->next = second;
first->next = second->next;
second->next = first;
tmp = first;
}
return
pre->next;
}