标签:bsp ret 很多 ext null int next pairs leetcode
链表题:
如果直接做会比较难处理头指针问题,一个好的方法是构造一个假的指针,指向head,然后再进行处理,这样会简便很多。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* swapPairs(ListNode* head) { 12 if(NULL==head || NULL==head->next) return head; 13 ListNode *mock_head = new ListNode(-1); 14 mock_head->next=head; 15 ListNode *flag_node=mock_head; 16 while(flag_node) { 17 vector<ListNode*> nodes; 18 do { 19 nodes.push_back(flag_node); 20 flag_node=flag_node->next; 21 } while (nodes.size()<3 && flag_node); 22 nodes.push_back(flag_node); 23 if (nodes.size()<4) break; 24 nodes[0]->next = nodes[2]; 25 nodes[1]->next = nodes[3]; 26 nodes[2]->next = nodes[1]; 27 flag_node = nodes[1]; 28 } 29 return mock_head->next; 30 } 31 };
[leetcode] Swap Nodes in Pairs
标签:bsp ret 很多 ext null int next pairs leetcode
原文地址:https://www.cnblogs.com/lidouer/p/9175922.html