[LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
来源:互联网 发布:淘宝搜相似图片搜索 编辑:程序博客网 时间:2024/05/07 18:07
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
分析:其实本题主要在考察链表逆序的问题。只是将长链表分多组逆序,多了每组逆序后,向前向后链接的步骤。
class Solution {public: ListNode *reverseKGroup(ListNode *head, int k) { ListNode *p=head,*q=head; ListNode *ghead,*gtail,*front=NULL,*back=NULL; while(p!=NULL){ int n=k-1; while(n--){ if(p->next==NULL) return head; p=p->next; }//p指向长度为k的group的tail ghead=q;gtail=p; back=p->next; if(ghead==gtail)return head; reverseList(ghead,gtail); ghead=p;gtail=q; //逆序后,收尾交换了 if(front==NULL){ //第一个分组 head=ghead; } else{ front->next=ghead; } front=gtail; gtail->next=q=p=back; } return head; }private: ListNode *reverseList(ListNode *head,ListNode *tail){ if(head==tail)return head; //只有一个值 tail=tail->next; ListNode *p,*q,*temp; p=head;q=head->next; while(q!=tail){ temp=q; q=q->next; temp->next=p; p=temp; } head->next=NULL; head=p; return head; }};
0 0
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- leetCode 25.Reverse Nodes in k-Group (以k个节点为一组反转链表) 解题思路和方法
- LeetCode 25 Reverse Nodes in k-Group K个一组反转节点
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- 链表编程题专题--Reverse Nodes in k-Group(最后几个节点不足一组的不逆序)
- Reverse Nodes in k-Group k个数为一组翻转结点
- leetcode:Reverse Nodes in k-Group(以k为循环节反转链表)【面试算法题】
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- MySQL 当记录不存在时插入,当记录存在时更新
- com.mysql.jdbc.exceptions.jdbc4.CommunicationsException||java.net.SocketException: Broken pipe
- 实现include和include_once
- 深入理解php原理之include include_once require require_once
- Jbuilder增加内存使用大小
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- 无限级分类,左右值算法
- iphone开发注意事项
- 预排序遍历树算法(非递归无限极分类算法)学习笔记
- 在xshell传输文件
- 使用var_dump打印数组
- C 调用外部方法
- zval_dtor与zval_ptr_dtor的区别
- mongoDB 入门指南、示例