标签:
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
这道题的意思就是k个为一组,然后进行翻转
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /* * 以k个节点为一组进行翻转,直到最末 */ ListNode* reverseKGroup(ListNode* head, int k) { if (NULL == head || 1 == k) { return head; } ListNode f(0); ListNode* node = &f; node->next = head; while (node && node->next) { ListNode* reverse_last; node->next = reverse(node->next, k, reverse_last); node = reverse_last; } return f.next; } /* * 翻转从p节点开始的k个节点 * 如果失败,就返回初始节点p的位置, 并不进行翻转 * 成功返回翻转后的开始节点 * @param p 开始节点 * @param k 翻转的节点个数 * @param last 翻转成功后的第k个节点,如果翻转失败,该值为NULL * */ ListNode* reverse(ListNode* p, int k, ListNode* &last) { int m = k; ListNode* q = p; //这里做遍历,如果不满足条件,就保持原样 while (m>1 && q){ q = q->next; m--; } if (m>1 || NULL == q) { last = NULL; return p; } //进行翻转 ListNode* pre = p; ListNode* c_node = p->next; ListNode* n_node = p->next->next; ListNode* q_next = q->next; while (pre != q) { c_node->next = pre; pre = c_node; c_node = n_node; n_node = n_node ? n_node->next : NULL; } p->next = q_next; last = p; return q; } };
标签:
原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5119755.html