Reverse Nodes in k-Group [LeetCode]
2013-10-17 14:11
204 查看
Problem Description: http://oj.leetcode.com/problems/reverse-nodes-in-k-group/
Basic Idea: Do it like reverse a linked list with a counter started by k. Record the tail at the first, then let the tail-> next be the head of rest linked list. This is the recursive version, which is much easier than interative version.
Basic Idea: Do it like reverse a linked list with a counter started by k. Record the tail at the first, then let the tail-> next be the head of rest linked list. This is the recursive version, which is much easier than interative version.
/** * 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) { if(k <= 1) return head; ListNode *iterate = head; int num = 0; while(iterate != NULL) { num ++; iterate = iterate -> next; } if(num < k) return head; ListNode * new_head = NULL; ListNode * tail = head; int count = k; while(head != NULL && count > 0) { ListNode *pre_head = new_head; new_head = head; head = head->next; count --; new_head->next = pre_head; } if(head != NULL) tail->next = reverseKGroup(head, k); return new_head; } };
相关文章推荐
- [leetcode 25]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group-按组翻转链表-链表操作
- [leetcode 25] Reverse Nodes in k-Group
- leetcode - Reverse Nodes in k-Group
- Leetcode: reverse-nodes-in-k-group
- leetcode | Reverse Nodes in k-Group
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- leetcode 25: Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- leetcode25: Reverse Nodes in k-Group
- Reverse Nodes in k-Group[leetcode]递归和非递归的解法
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- LeetCode 25: Reverse Nodes in k-Group
- Leetcode_reverse-nodes-in-k-group
- 2017-09-11 LeetCode_025 Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group K个一组反转节点
- LeetCode-Reverse Nodes in k-Group
- leetcode (25) - Reverse Nodes in k-Group