标签:
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 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5769609.html