反转链表与反转链表中的某一段

描述:

反转链表。请使用一趟扫描完成反转。

实现:

 public static void main(String[] args) {
        Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, new Node(6, null))))));
        System.out.println(reverse(head));
}
private static Node reverse(Node head) {
    if(head==null){
        return null;
    }
    Node previous = null;//将null节点当作head的上一节点
    Node current = head, next;
    while (current != null) {
        //拿到剩下节点们的头节点
        next = current.nextNode;
        //反转当前节点指向前一节点
        current.nextNode = previous;
        //更新到下一组位置
        previous = current;
        current = next;
    }
    return previous;
}

描述:

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:

1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

实现:

思路:使用迭代的方式,通过使用两个 Node 来标记反转链表的头和尾,大体思路和反转链表时一致,且该方法空间复杂度较低为O( 1 ),时间复杂度为O( N )。

public static void main(String[] args) {
        Node head1 = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, new Node(6, null))))));
        System.out.println(reverseBetween(head1, 1, 3));
}

private static Node reverseBetween(Node head, int startIndex, int endIndex) {
    //初始化一个节点来避免startIndex=1时出现空指针异常
    Node nullNode=new Node(1, head);
    Node current=nullNode;
    for (int i = 1; i < startIndex ; i++) {//找到要反转区域的上一个节点
        current = nullNode.nextNode;
    }

    Node previous = null,next=null, endPre, start;//双指针记录起始的两个节点的前节点
    endPre = current;//开始反转的前一个节点
    start = current = current.nextNode;//反转的头节点
    while (startIndex != endIndex+1){
        //修改当前节点指向上一节点,期间使用三个变量来保存前中后节点
        next = current.nextNode;
        current.nextNode = previous;
        previous = current;
        current = next;

        startIndex++;
    }
    //将反转的起点的下一节点指向
    start.nextNode = current;
    endPre.nextNode = previous;

    return nullNode.nextNode;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值