連結串列中每k個節點逆序
阿新 • • 發佈:2019-01-13
/** * 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 *h=head; if(head==NULL||head->next==NULL){ return head; } // ListNode *h=head; stack<int> st; while(h){ ListNode *temp=h; for(int i=0;i<2;++i){ if(h){ st.push(h->val); }else{ return head; } h=h->next; } while(!st.empty()){ temp->val=st.top(); st.pop(); temp=temp->next; } } return head; } };