leetcode链表--15、reverse-nodes-in-k-group(按照k值进行k个结点的逆序)
题目描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:1->2->3->4->5
For k = 2, you should return:2->1->4->3->5
For k = 3, you should return:3->2->1->4->5
解题思路:本题借鉴链表的逆序的思路,中间使用栈进行存储
1)定义tmp记录目前存入栈s中的结点个数,如果tmp<k,中存入栈s中
2)tmp == k时,就将栈s中的结点弹出,链接在新链表p上,以上1) 2)完成一次k个结点的操作
3)当所有结点遍历完成,有两种情况,一种恰好剩k个结点,一种剩少于k个结点
对于恰好剩k个结点,则弹出s,链接在新链表上
对于少于k个结点,则不需要逆序,因此定义另外一个栈s1顺序变回来,然后再链接在新链表上
4)h1->next = NULL,且返回head->next
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 };