题解 | #BM3 链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { ListNode top = new ListNode(0); ListNode pre=top; ListNode tail = top; if(k<2){ return head; } int i=1; while( head!=null ){ if(i==k+1){ pre=tail; i=1; } if(i==1){ tail = head; } ListNode temp = head.next; head.next = pre.next; pre.next = head; head = temp; i++; } if(i<=k&&i>2){ head = pre.next; pre.next=null; while(head!=null){ ListNode temp = head.next; head.next = pre.next; pre.next = head; head = temp; } } return top.next; } }
解体思路:不管是不是满足k个,直接反转。最后判断最后一个是不是k个,如果不满足k,则再反转回去即可。