【leetcode】【单链表】【25】Reverse Nodes in k-Group
#include<iostream> #include<stack> #include<memory> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: pair<ListNode*,ListNode*> reverseList(ListNode* head) { if (head == NULL || head->next == NULL) return pair<ListNode*, ListNode*>(head, head); ListNode* cur = head; ListNode* newHead = NULL; ListNode* temp = NULL; while (cur){ temp = cur; cur = cur->next; temp->next = newHead; newHead = temp; } return pair<ListNode*, ListNode*>(newHead, head); //返回反转后的头结点和尾结点(尾节点不是NULL,是NULL前面一个节点) } ListNode* reverseKGroup(ListNode* head, int k) { if (head == NULL || head->next == NULL) return head; int numOfNodes = 0; //链表长度 ListNode* cur = head; while (cur){ ++numOfNodes; cur = cur->next; } if (numOfNodes < k || k==1) //长度小于k或者k==1直接返回 return head; int kgroup = numOfNodes / k; //分为几组 ListNode* temp = new ListNode(0); ListNode* beforeHead = temp; ListNode* newHead = NULL; ListNode* newTail = NULL; while (kgroup>0){ newHead = cur = head; for (int i = 1; i < k; ++i) cur = cur->next; head = cur->next; cur->next = NULL; pair<ListNode*, ListNode*> pr = reverseList(newHead); newHead = pr.first; newTail = pr.second; ////for test //ListNode* aa = newHead; //while (aa){ // cout << aa->val << " "; // aa = aa->next; //} //cout << endl; temp->next = newHead; temp = newTail; --kgroup; } if (head) temp->next = head; head = beforeHead->next; delete beforeHead; return head; } ListNode* createList(ListNode* head){ int numOfNode; int value; cout << "please input number of listNode:"; cin >> numOfNode; cin >> value; head = new ListNode(value); ListNode* cur = head; for (int i = 1; i < numOfNode; ++i){ cin >> value; ListNode* temp = new ListNode(value); cur->next = temp; cur = temp; } return head; } void printNode(ListNode* head){ ListNode* cur = head; while (cur){ cout << cur->val << " "; cur = cur->next; } cout << endl; } }; int main(){ ListNode* head = NULL; Solution solution; head = solution.createList(head); solution.printNode(head); head = solution.reverseKGroup(head,3); solution.printNode(head); system("pause"); return 0; }
posted on 2015-06-03 19:24 ruan875417 阅读(121) 评论(0) 编辑 收藏 举报