因为不太熟悉链表操作,所以解决方法烦了点,空间时间多有冗余。
代码中l,r分别是每一组的需要交换的左右指针,temp是下一组的头指针,用于交换后链接;res是交换后的l指针,用于本组交换后尾指针在下一组交换后链接上交换后的头指针。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* l = head; ListNode* r = head; if(head == NULL || head->next == NULL)return head; ListNode* res = NULL; r = r->next; head = r; ListNode* temp; while(r != NULL) { temp = r->next; l->next = r->next; r->next = l; if(r != NULL && res != NULL)res->next = r; res = l; if(temp == NULL) break; l = temp; r = l->next; } return head; } };
讨论中看到比较简洁的解法,但可能消耗资源较多:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode **pp = &head, *a, *b; while ((a = *pp) && (b = a->next)) { a->next = b->next; b->next = a; *pp = b; pp = &(a->next); } return head; } };