您的位置:首页 > Web前端 > Node.js

Leetcode: Reverse Nodes in k-Group

2015-06-13 15:43 621 查看


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节点一组进行翻转
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;
}
}
}



 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息