题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

一段一段的反转


/*
 * 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) {
        // write code here
        if(k==1||head==null)
            return head;
        ListNode dummyNode=new ListNode(-1);
        dummyNode.next=head;
        ListNode p=dummyNode;
        ListNode rear=dummyNode.next;
        ListNode p2;
        int count=1;
        while (rear!=null){
            if(count%k==0){
         //       System.out.println(count+" "+rear.val);
                ListNode p1=p.next;
                p2=rear.next;
                rear.next=null;                
                p.next=reverse(p1);
                p1.next=p2;
                p=p1;
                rear=p1;
            }
            rear=rear.next;
            count++;
        }
        return dummyNode.next;
    }
    public ListNode reverse(ListNode head) {
        ListNode p=head;
        ListNode hh=new ListNode(0);
        while(p!=null){
            ListNode cur=p.next;
            p.next=hh.next;
            hh.next=p;
            p=cur;
        }
        return hh.next;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务