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

LeetCode算法题目:Reverse Nodes in k-Group

2017-04-05 15:48 405 查看

题目:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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

分析:

知道了翻转链表的通用写法之后,解这一题其实就是循环翻转的过程(知道最后一个group长度不足)。

先介绍下翻转链表的写法:

首先设置一个前置节点,将前置节点的next设置为头节点,以头节点为当前节点,开始循环

将当前节点的next赋给一个临时节点,然后将当前节点的next指向前置节点,随后依次位移前置节点指针和当前节点指针:前置节点指针指向当前节点,当前节点指针指向临时节点,这样就完成了一次循环

当前置节点指针指向尾节点时,循环结束

有个这个翻转函数之后,只要对链表进行循环,当计数长度不k时,指针继续前进;当计数长度到达k时,将头尾节点作为参数传入翻转函数进行翻转,然后重新拼接到原链表中。直至到达链表末尾。

代码:

/**
* 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)
{
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
int count = 0;
ListNode pre = dummy;
ListNode cur = head;
while(cur != null)
{
count ++;
ListNode next = cur.next;
if(count == k)
{
pre = reverse(pre, next);
count = 0;
}
cur = next;
}
return dummy.next;
}
private ListNode reverse(ListNode pre, ListNode end)
{
if(pre==null || pre.next==null)
return pre;
ListNode head = pre.next;
ListNode cur = pre.next.next;
while(cur!=end)
{
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = next;
}
head.next = end;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法