菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
81
0

Reverse Nodes in k-Group

原创
05/13 14:22
阅读数 24767

标签:des   style   blog   class   code   java   

Link: http://oj.leetcode.com/problems/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

bubuko.com,布布扣
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseKGroup(ListNode head, int k) {
14         if (head == null || head.next == null)
15             return head;
16         ListNode pre = new ListNode(0);
17         pre.next = head;
18         head = pre;
19         int index = 1;
20         ListNode cur = pre.next;
21         ListNode post = cur.next;
22         //before execution, we need to check if there‘s enough element
23         while (enoughElement(cur, k)) {
24             while (index < k) {
25                 ListNode temp = post.next;
26                 post.next = pre.next;
27                 cur.next = temp;
28                 pre.next = post;
29                 post = temp;
30                 index++;
31             }
32             //after the reverse operation,we need to initial
33             //the parameter
34             index = 1;
35             pre = cur;
36             cur = cur.next;
37             //note the cur may be null
38             if (cur != null) {
39 
40                 post = cur.next;
41             }
42         }
43         return head.next;
44 
45     }
46 
47     public boolean enoughElement(ListNode head, int k) {
48         int count = 0;
49         //note the head could be null, then we cannot use head.next
50         while (head != null) {
51             head = head.next;
52             count++;
53         }
54         if (count < k)
55             return false;
56         return true;
57 
58     }
59 }
bubuko.com,布布扣

 

For the basic idead of the algorithm, please refer to http://www.cnblogs.com/Altaszzz/p/3704780.html

 

 

Reverse Nodes in k-Group,布布扣,bubuko.com

Reverse Nodes in k-Group

发表评论

0/200
81 点赞
0 评论
收藏
为你推荐 换一批