Leetcode: Reverse Nodes in k-Group
2015-06-13 15:43
621 查看
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节点一组进行翻转
1. 其实这个题目跟之前的Swap Nodes in Pairs有点像,那题是两个一组交换,这题是k个一组逆序
2. 首先得根据给出的k值对节点进行划分,注意划分时边界的处理
3. 对划分好的节点进行反转,然后重新接回原链表即可,注意对头节点的处理
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head==null||head.next==null||k==1)return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode tail = head; int count = 0; while(tail!=null) { count++; if(count==k) { reverse(head,tail); pre.next = tail; pre = head; head = pre.next; tail = pre.next; count = 1; } if(tail!=null)tail = tail.next; } return dummy.next; } private void reverse(ListNode head, ListNode tail) { ListNode curr = head; ListNode next = head.next; curr.next = tail.next; tail.next = null; while(next!=null) { ListNode tmp = next.next; next.next = curr; curr = next; next = tmp; } } }
相关文章推荐
- [C/C++]反转链表
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- 找出链表倒数第n个节点元素的二个方法
- Java数据结构之简单链表的定义与实现方法示例
- C语言单循环链表的表示与实现实例详解
- PHP小教程之实现链表
- C语言双向链表的表示与实现实例详解
- C语言实现输出链表中倒数第k个节点
- C++语言实现线性表之链表实例
- STL list链表的用法详细解析
- C语言创建链表错误之通过指针参数申请动态内存实例分析
- 编码实现从无序链表中移除重复项(C和JAVA实例)
- Java采用循环链表结构求解约瑟夫问题
- Python实现的数据结构与算法之链表详解
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1