LeetCode_Reverse Nodes in k-Group
2013-08-15 21:27
417 查看
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
/** * 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(k <= 0 || head == NULL) return head; int len = 0, tempK; ListNode *p, *cur,*q , *pre ,*tail; q = head; while(q){ len++; q = q->next; } if(len < k) return head; cur = head; pre = NULL; while(len >= k){ tempK = 0; p = NULL; while( tempK < k){ if(p == NULL){ p = cur; tail = cur; cur = cur->next; }else{ q = cur->next; cur->next = p; p = cur; cur = q; } tempK++; } if(pre == NULL) head = p; else pre ->next = p; pre = tail; pre->next = cur; len = len - k; } return head; } };
相关文章推荐
- 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 】 python 实现
- 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 每k个一组反转链表
- leetcode25---Reverse Nodes in k-Group
- LEETCODE: Reverse Nodes in k-Group
- LeetCode[Linked List]: Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group(15-10-11)
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- leetcode-25 Reverse Nodes in k-Group
- Reverse Nodes in k-Group --leetcode
- leetcode Reverse Nodes in k-Group python
- LeetCode 25: Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group