(链表) leetcode 25. Reverse Nodes in k-Group
解法一:用栈来实现链表反转
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { // O(k) 空间复杂度 if(!head) return NULL; ListNode dummy(0); stack<ListNode*> st; dummy.next = head; ListNode* cur = &dummy, *next = head; while(next){ for(int i=0; i<k && next; ++i){ st.push(next); next = next->next; } if(st.size() != k) return dummy.next; //剩下的元素<k个 while(st.size()){ cur->next = st.top(); st.pop(); cur = cur->next; } cur->next = next; } 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* reverseKGroup(ListNode* head, int k) { //k为需要reverse的个数 //无辅助空间 if(head == NULL) return NULL; ListNode dummy(0); dummy.next = head; ListNode* pre = &dummy; while(pre){ pre = reverse(pre, k); } return dummy.next; } ListNode* reverse(ListNode* pre, int k){ ListNode* last = pre; //pre始终指向区间的前一个结点 for(int i=0; i<=k; i++){ last = last->next; //last指向k区间的下一个元素 if(i!=k && last==NULL) //区间内不够k个 return NULL; //返回 } ListNode* tail = pre->next; ListNode* cur = tail->next; while(cur!=last){ ListNode* next = cur->next; cur->next = pre->next; pre->next = cur; tail->next = next; cur = next; } return tail; } };