首页 > 代码库 > Swap Nodes in Pairs
Swap Nodes in Pairs
思路一:记录遍历列表过程中奇偶性,然后进行交换
/** * 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; } };
Swap Nodes in Pairs
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。