《程序员代码面试指南》第二章 链表问题 将单链表每K个节点之间逆序

样例

链表1-2-3-4-5-6-7-8-9-10  K=3 ,结果 3-2-1-6-5-4-9-8-7-10

java代码

/**
 * @Description:将单链表每K个节点之间逆序
 * @Author: lizhouwei
 * @CreateDate: 2018/4/7 9:10
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter2_12 {

    public Node reverseK(Node head, int k) {
        if (head == null || k < 0) {
            return null;
        }
        Node preNode = null;//开始反转的前驱结点
        Node startNode = null;//开始反转的节点
        Node endNode = null;//结束反转的节点
        Node postNode = null;//结束反转的后继节点
        int count = 0;
        Node cur = head;
        Node next = null;
        while (cur != null) {
            count++;
            next = cur.next;
            if (count == k) {
                //如开始节点为空,说明是第一次反转,开始节点为head,后面反转时都是不为空的
                startNode = preNode == null ? head : preNode.next;
                //如开始节点为空,说明是第一次反转,最终开始节点变为第一次反转时的end节点
                head = preNode == null ? cur : head;
                reverse(preNode, startNode, cur, next);
                preNode = startNode;//反转后,下次反转的前驱结点为现在的startNode 开始节点
                count = 0;
            }
            cur = next;
        }

        return head;
    }

    //部分反转
    public void reverse(Node pre, Node start, Node end, Node post) {
        Node cur = start.next;
        start.next = post;
        Node next = null;
        while (cur != post) {
            next = cur.next;
            cur.next = start;
            start = cur;
            cur = next;
        }
        //start不是head
        if (pre != null) {
            pre.next = end;
        }
    }

    //测试
    public static void main(String[] args) {
        Chapter2_12 chapter = new Chapter2_12();
        Link link = new Link();
        //构造链表
        for (int i = 10; i > 0; i--) {
            link.add(i);
        }
        Link.printLink(link.head);
        Node head = chapter.reverseK(link.head, 3);
        Link.printLink(head);
    }
}
posted @ 2018-04-07 10:01  lizhouwei  阅读(125)  评论(0编辑  收藏  举报