[leetcode 25] Reverse Nodes in k-Group
2014-12-06 15:13
645 查看
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:
[Solution]
每次访问连续的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
[Solution]
每次访问连续的k个节点,将k个节点逆置。
注意首位节点的衔接。
ListNode *reverseKGroup(ListNode *head, int k) { if (k <= 1 || head == NULL) return head; ListNode *dummy = new ListNode(INT_MIN); dummy->next = head; ListNode *p, *q, *tmp_head, *tmp_tail; int i = 0; p = dummy; tmp_head = dummy; while (p != NULL) { if (i == k) { q = p->next; p->next = NULL; tmp_tail = tmp_head->next; tmp_head->next = reverse(tmp_head->next); p = tmp_tail; p->next = q; tmp_head = p; i = 0; } else { i++; p = p->next; } } head = dummy->next; delete dummy; return head; } ListNode *reverse(ListNode *head) { ListNode *p = NULL, *q, *r; q = head; if (q == NULL) return NULL; r = q->next; while (r != NULL) { q->next = p; p = q; q = r; r = r->next; } q->next = p; return q; }
相关文章推荐
- leetcode 25: Reverse Nodes in k-Group
- LeetCode (25) Reverse Nodes in k-Group (链表)
- LeetCode 25: Reverse Nodes in k-Group
- leetcode-25 Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group
- 【leetcode】【单链表】【25】Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group
- LeetCode(25)Reverse Nodes in k-Group
- LeetCode_25---Reverse Nodes in k-Group
- leetcode_25题——Reverse Nodes in k-Group (链表)
- LeetCode 25 - Reverse Nodes in k-Group
- [LeetCode]25 Reverse Nodes in k-Group
- Leetcode 25 Reverse Nodes in k-Group
- leetcode_25_Reverse Nodes in k-Group
- leetcode 25 Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group (C,C++,Java,Python)
- [leetcode-25]Reverse Nodes in k-Group(C)
- [leetcode 25]Reverse Nodes in k-Group
- leetcode 25 -- Reverse Nodes in k-Group