LeetCode : Reverse Nodes in k-Group
2012-12-06 16:20
281 查看
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:
For k = 2, you should return:
For k = 3, you should return:
刚开始没理解题意。其实就是k个k个做。和之前那个差不多。
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个k个做。和之前那个差不多。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function if(head == NULL){return NULL;} int count = 0; ListNode * p1 = head; while(p1){ count++; p1 = p1->next; } if(count < k){return head;} p1 = head; ListNode * last = p1; ListNode * p2 = p1->next; ListNode * p3; if(p2 == NULL){ return head; } int i = 1; for(i = 1 ; i< k && p1 && p2; ++i){ p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = p2; if(count - k >= k){ last->next = reverseKGroup(last->next, k); } return p1; } };
相关文章推荐
- LeetCode(25)Reverse Nodes in k-Group
- LeetCode--reverse-nodes-in-k-group
- LeetCode 25:Reverse Nodes in k-Group
- Reverse Nodes in k-Group leetcode java
- LeetCode-Reverse Nodes in k-Group
- Reverse Nodes in k-Group,LeetCode
- LeetCode 25 Reverse Nodes in k-Group Add to List (划分list为k组)
- LeetCode(6) - Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- DAY27:leetcode #25 Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group
- Reverse Nodes in k-Group -- LeetCode
- Reverse Nodes in k-Group leetcode
- 【LeetCode】Swap Nodes in Pairs & Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group
- leetcode problem: Reverse Nodes in k-Group
- LeetCode - Refresh - Reverse Nodes in k-Group
- LeetCode (25) Reverse Nodes in k-Group (链表)