首页 > 代码库 > Reverse Nodes in k-Group
Reverse Nodes in k-Group
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
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 }
For the basic idead of the algorithm, please refer to http://www.cnblogs.com/Altaszzz/p/3704780.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。