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:
Given1->2->3->4
You should return the list as2->1->4->3
Given1->2->3
You should return the list as2->1->3
难度不大
方法一:二级指针交换
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void
swap_ptr(struct ListNode** head) {
struct ListNode* temp = (*head)->next;
(*head)->next = (*head)->next->next;
temp->next = *head;
*head = temp;
}
struct ListNode* swapPairs(struct ListNode* head) {
if (!head || !head->next)
return head;
if (!head->next->next) {
swap_ptr(&head);
return head;
}
head->next->next = swapPairs(head->next->next);
swap_ptr(&head);
return head;
}
方法二:一级指针交换
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void*
swap_ptr(struct ListNode* first, struct ListNode* second) {
first->next = second->next;
second->next = first;
return second;
}
struct ListNode* swapPairs(struct ListNode* head){
if (!head || !head->next)
return head;
if (!head->next->next)
return (struct ListNode*)swap_ptr(head, head->next);
head->next->next = swapPairs(head->next->next);
return (struct ListNode*)swap_ptr(head, head->next);
}