解法一:递归
public: ListNode* swapPairs(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* new_head = head->next; head->next = swapPairs(new_head->next); new_head->next = head; return new_head; }};解法二:非递归
class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode* new_head = NULL; ListNode** pp = &new_head; while(head != NULL){ if(head->next == NULL){ *pp = head; break; } else{ *pp = head->next; head->next = (*pp)->next; (*pp)->next = head; pp = &(head->next); head = head->next; } } return new_head; }};新闻热点
疑难解答