思路一:记录遍历列表过程中奇偶性,然后进行交换
/** * 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) { if(head == nullptr || head->next == nullptr) return head; ListNode dummy(-1); dummy.next = head; ListNode *cur = head->next; ListNode *curLeft = &dummy; int count = 2; while(cur) { if(count % 2 == 0) { curLeft->next->next = cur->next; cur->next = curLeft->next; ListNode *tmp = curLeft->next; curLeft->next = cur; curLeft = tmp; cur = cur->next; } cur = cur->next; ++count; } return dummy.next; } };
思路二:上面思路中使用两个指针,但实际使用三个指针会方便很多
/** * 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) { if(head == nullptr || head->next == nullptr) return head; ListNode dummy(-1); dummy.next = head; for(ListNode *prev = &dummy, *cur=head, *next=head->next; next; prev=cur, cur=cur->next, next=cur ? cur->next:nullptr) { cur->next = next->next; next->next = cur; prev->next = next; } return dummy.next; } };
时间: 2024-10-18 08:51:12