http://oj.leetcode.com/problems/reverse-nodes-in-k-group/ 链表 指针
对链表翻转的变形
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *reverse(ListNode * l2) { ListNode *n1,*n2,*before; n1 = l2; n2 = n1->next; before = NULL; while(n2) { n1->next = before; before = n1; n1 = n2; n2 = n2->next; } n1->next = before; return n1; } class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { if(k==1 || head == NULL) return head; ListNode *ans,*ansTail; bool firstTime = 1,flagContinue = 1; ListNode *seghead, *tempNode = head; while(flagContinue && tempNode) { seghead = tempNode = head; flagContinue = 0; int times = 0; while(tempNode) { tempNode = tempNode->next; times++; if(times == k-1 && tempNode) { flagContinue = 1; break; } } //break up if(tempNode) { head = tempNode->next; tempNode->next = NULL; } if(flagContinue) { seghead = reverse(seghead); } if(firstTime) { ans = ansTail = seghead; firstTime = false; } else ansTail->next = seghead; while(ansTail->next) ansTail = ansTail->next; } return ans; } }; int main() { ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(2); ListNode *n3 = new ListNode(3); ListNode *n4 = new ListNode(4); ListNode *n5 = new ListNode(5); n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; ListNode *ans; Solution myS; ans = myS.reverseKGroup(NULL,6); return 0; }