左程云_算法与数据结构 — 链表问题 — 05反转部分单链表

问题描述

给定头节点head,两个整数from和to,要求在单向链表上把第from到to个节点之间的部分进行反转。

思路分析

  1. 对输入的from和to进行合理性的判断:
    遍历链表求出len,1<=from<=to<=len;
    同时确定好from的前一个几点和to的下一个节点;
  2. 对head节点的重定义:
    当在from是要从头开始反转的时候,head应该等于to节点;
    若不是则保持原来的节点;
  3. 对from和to之间的节点进行反转,参考04问题反转链表思想;

代码实现

package algorithm_zuochengyun;

public class CH2_05_reversePart {

    public static Node reversePart(Node head, int from, int to) {
        System.out.println("将以head为头节点的链表从第" + from + "个到第" + to + "个之间进行反转。");
        int len = 0;
        Node fpre = null;
        Node tpos = null;
        Node curNode = head;
        // 确定len和fpre,tpos结点;
        while (curNode != null) {
            len++;
            // a?b:c 在这里如果c写null那么当len增大
            // 到不符合情况的时候他们就会被设置为null
            fpre = len == from - 1 ? curNode : fpre;
            tpos = len == to + 1 ? curNode : tpos;
            curNode = curNode.next;
        }
        // 对输入的from,to进行错误检测
        if (from < 1 || from >= to || to > len) {
            System.out.println("illegle input of from or to .");
            return null;
        }
        // 对from到to的结点进行反转
        Node node1 = null;
        Node node2 = null;
        Node next = null;
        // 首先确定是否从头节点开始反转
        node1 = fpre == null ? head : fpre.next;
        node2 = node1.next;
        // 因为node1=node(from)
        // 在最后反转完之后node1是正好在tpos前一个
        node1.next = tpos;
        // 开始反转
        while (node2 != tpos) {
            next = node2.next;
            node2.next = node1;
            node1 = node2;
            node2 = next;
        }
        // 对反转完之后链表头进行设置
        if (fpre != null) {
            fpre.next = node1;
            return head;
        }
        return node1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Node head = Node.init();
        Node.Print(head);
        Node.Print(reversePart(head, 3, 5));
    }

}

实现结果

这里写图片描述

问题总结

要注意对细节和边界问题的完善,代码要对特殊例子普遍性覆盖;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值