Reverse Nodes in k-Group
来源:互联网 发布:网络投标书 编辑:程序博客网 时间:2024/06/15 20:09
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
在每一组reverse时候:例如X->1->2->3, k=2
X是人为设置的一个头节点(每一组逆序都是如此),然后tail=1,cur=2,next=3;
1. 2->next=1(cur->[X->next])
2. X->next=2 (X->next=cur)
3. 2=3(cur=next)此时的cur为下一组的起始点。
4. tail->next=下一组的头
int list_length(ListNode *head){ int i = 0; while (head) { i++; head = head->next; } return i;}ListNode *reverse_list(ListNode *head){ if (head == NULL || head->next == NULL) return head; ListNode *pre = NULL, *cur = head, *next; while (cur != NULL) { next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre;}ListNode *reverseKGroup(ListNode *head, int k){ if (list_length(head) < k || k < 2) return head; ListNode *newhead = head, *tail = head, *next_ghead; for (int i = 0; i < k - 1; ++i) { tail = tail->next; } next_ghead = tail->next; tail->next = NULL; tail = reverse_list(newhead); newhead->next = reverseKGroup(next_ghead, k); return tail;}
0 0
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- NSStream
- 用SecureCRT连接虚拟机linux-hostonly方式整理
- stanford第二课“文本处理基础(Basic Text Processing)”
- 2011 多项式求和
- iOS SDK:那些关于iOS调试的技巧
- Reverse Nodes in k-Group
- 最大子矩阵和
- cuteftp不能上传文件到ubuntu问题
- km算法
- 培训经理辞职引发的讨论
- 数据结构-层次遍历二叉树
- GDB 进行调试 使用心得
- 2012 素数判定
- 无线漫游