标签:while space struct end his its blog modified node
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 *reverseKGroup(ListNode *head, int k) { 12 if(head == NULL || k<=1) 13 return head; 14 ListNode *pNode = head; 15 stack<ListNode *> s; 16 stack<ListNode *> s1; 17 int tmp = 0; 18 ListNode *h = new ListNode(0); 19 ListNode *h1 = h; 20 while(pNode) 21 { 22 if(tmp < k) 23 { 24 s.push(pNode); 25 pNode = pNode->next; 26 tmp++; 27 } 28 else 29 { 30 while(!s.empty()) 31 { 32 h1->next = s.top(); 33 s.pop(); 34 h1 = h1->next; 35 } 36 tmp = 0; 37 } 38 } 39 if(tmp == k) 40 { 41 while(!s.empty()) 42 { 43 h1->next = s.top(); 44 s.pop(); 45 h1 = h1->next; 46 } 47 } 48 else 49 { 50 while(!s.empty()) 51 { 52 s1.push(s.top()); 53 s.pop(); 54 } 55 while(!s1.empty()) 56 { 57 h1->next = s1.top(); 58 s1.pop(); 59 h1 = h1->next; 60 } 61 } 62 h1->next = NULL; 63 return h->next; 64 } 65 };
leetcode链表--15、everse-nodes-in-k-group(按照k值进行k个结点的逆序)
标签:while space struct end his its blog modified node
原文地址:http://www.cnblogs.com/qqky/p/6912543.html