leetcode:Reverse Nodes in k-Group
2015-08-19 17:33
696 查看
Reverse Nodes in k-Group
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个节点,翻转K个节点时,记录K个翻转后节点的头节点指针和尾节点指针。
C++代码
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个节点,翻转K个节点时,记录K个翻转后节点的头节点指针和尾节点指针。
C++代码
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode*p,*q1=head,*lastNode=head,*q2,*last; if (!head||k==0) return head; q2 = nodeAfterKNodes(q1, k); head = reverseList(q1, k, last); lastNode = last; q1 = q2; while (q1){ q2 = nodeAfterKNodes(q1, k); lastNode->next= reverseList(q1, k, last); lastNode = last; q1 = q2; } return head; } ListNode* reverseList(ListNode* head,int k,ListNode*& last){ if (!head || k > length(head)){ last = head; return head; } ListNode* p = head, *q=NULL, *r=NULL; last = head; p = head; q = head->next; head->next = NULL; if (q) r = q->next; int i = 0; while (q && i<k-1){ q->next = p; p = q; q = r; if (r) r = r->next; i++; } return p; } int length(ListNode* head){ int len = 0; while (head){ len++; head = head->next; } return len; } ListNode* nodeAfterKNodes(ListNode* head, int k){ if (k > length(head)) return NULL; int i = 0; while (i < k){ head = head->next; i++; } return head; } };
相关文章推荐
- LINK : warning LNK4098: 默认库“LIBCMTD”与其他库的使用冲突;请使用 /NODEFAULTLIB:library
- 初学node---1
- Node开发入门
- Lavarel 后台组件frozenode的使用
- nodejs 的序列化与反序列化
- 7天学会NodeJs(里面讲了很多,最后一个大例子,更是讲了一些工程开发流程,很有收获)
- Node开发入门
- nodejs npm常用命令
- node.js基础:模块的创建和引入
- RT-Thread finsh源码分析: finsh_node.c
- RT-Thread finsh源码分析: finsh_node.h
- leetcode-024 Swap Nodes in Pairs
- Count Complete Tree Nodes
- GDataXMLNode
- [Leetcode] Count Complete Tree Nodes
- LightOJ 1094 - Farthest Nodes in a Tree
- nodejs中如何创建和加载模块
- lightoj1094 - Farthest Nodes in a Tree
- HTML DOM nodeType 属性
- [LeetCode 237] Delete Node in a linked list