/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
typedef struct ListNode* ListNode;
ListNode shead = (ListNode*)malloc(sizeof(struct ListNode));//一个坑
shead->next = head;
ListNode cur = shead;
while(cur->next != NULL && cur->next->next != NULL){
ListNode tmp = cur->next;
ListNode tmp1 = tmp->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
tmp->next = tmp1;
cur = cur->next->next;
}
return shead->next;
}
补充从大佬那里学来的递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
typedef struct ListNode* ListNode;
if(head == NULL || head->next == NULL){
return head;
}
ListNode nhead = head->next;
head->next = swapPairs(nhead->next);
nhead->next = head;
return nhead;
}