《程序员代码面试指南》第二章 链表问题 反转部分单向链表

题目

给一个单向链表和开始和结束的位置,将这两位置区间链表进行反转

java代码

/**
 * @Description:反转部分单向链表
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 20:30
 * @Modify by:
 * @ModifyDate:
*/
public class Chapter2_7 {

    public Node reversePart(Node head, int startIndex, int endIndex) {
        if (head == null || startIndex <= 0 || startIndex > endIndex) {
            return head;
        }
        Node preNode = null;//开始链表的前驱节点
        Node postNode = null;//结束节点的后继节点
        int len = 0;//链表长度
        Node cur = head;
        while (cur != null) {
            len++;
            preNode = len == startIndex - 1 ? cur : preNode;
            postNode = len == endIndex + 1 ? cur : postNode;
            cur = cur.next;
        }
        if(startIndex>len){
            return head;
        }
        Node node1 = preNode==null?head:preNode.next;
         Node node2 =node1.next;
        node1.next = postNode;
        Node next=null;
        while (node2!=postNode){
            next =  node2.next;
            node2.next =node1;
            node1 =node2;
            node2 = next;
        }
        //若preNode !=null,则不是从head开始反转的,链表头部依然是head
        if (preNode!=null){
            postNode.next = node1;
            return head;
        }
        //若preNode =null,则是从head开始反转的
        return node1;
    }

    //测试
    public static void main(String[] args) {
        Chapter2_7 chapter = new Chapter2_7();
        Link link = new Link();
        //构造两个链表
        for (int i = 10; i > 0; i--) {
            link.add(i);
        }
        Link.printLink(link.head);
        Node head = chapter.reversePart(link.head,1,5);
        Link.printLink(head);
    }
}
posted @ 2018-04-06 21:11  lizhouwei  阅读(143)  评论(0编辑  收藏  举报