Given a linked list, swap every two adjacent nodes and return its head.
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.
Subscribe to see which companies asked this question
这个也就是改天两个相邻的节点的值
这段代码使用的试类似交换两个数的值,然后使用了递归,
代码:
/**
* 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 *tmp=head->next;
head->next=swapPairs(tmp->next);
tmp->next=head;
return tmp;
}