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

LeetCode 128 Reverse Nodes in k-Group

2014-11-01 11:01 337 查看
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个的节点不旋转。

链表操作时,新建一个dummy头节点是很有好处的。

一个pre节点指向需要旋转的链表前一个节点,往后数k,next指向需要旋转地链表后一个节点,则中间的一部分就是常规的链表翻转操作。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null || k==1)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;//指向当前要翻转链表的前一个节点

int i=0;
while(head != null){
i++;
if(i%k == 0){//到了k的倍数
pre = reverse(pre, head.next);
head = pre.next;
}else
head = head.next;
}
return dummy.next;
}
//pre指向翻转链表之前一个节点,next指向翻转链表之后一个节点
public ListNode reverse(ListNode pre, ListNode next){
ListNode last = pre.next;
ListNode curr = last.next;
while(curr != next){
last.next = curr.next;
curr.next = pre.next;
pre.next = curr;
curr = last.next;
}
return last;//指向当前链表尾,即下一个链表头节点的前一个节点
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息