码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Nodes in k-Group

时间:2016-08-14 11:29:40      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode reverseKGroup(ListNode head, int k) {
11         if (head == null || head.next == null || k <= 1) {
12             return head;
13         }
14         ListNode dummy = new ListNode(0);
15         dummy.next = head;
16         head = dummy;
17         while (head.next != null) {
18             head = reverseNextK(head, k);
19         }
20         return dummy.next;
21     }
22     
23     //reverse head-->n1-->n2-->..->nk-->nNext
24     //to head-->nk-->nk-1-->..-->n1-->nNext
25     //return n1
26     private ListNode reverseNextK(ListNode head, int k) {
27         ListNode next = head;
28         //check  there is enought nodes to reverse
29         for (int i = 0; i < k; i++) {
30             if (next.next == null) {
31                 return next;
32             }
33             next = next.next;
34         }
35         
36         //reverse
37         ListNode node = head.next;
38         ListNode preNode = head, curt = head.next;
39         for (int i = 0; i < k; i++) {
40             ListNode temp = curt.next;
41             curt.next = preNode;
42             preNode = curt;
43             curt = temp;
44         }
45         head.next = preNode;
46         node.next = curt;
47         return node;
48     }
49 }

 

Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5769609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!