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

来源:互联网 发布:淘宝客服自动核对地址 编辑:程序博客网 时间:2024/06/08 11:09

问题描述

给定头节点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
原创粉丝点击