左程云_算法与数据结构 — 链表问题 — 04反转单向和双向链表

问题描述

实现反转链表的方法,要求时间复杂度为O(N),空间复杂度为O(1)

思路分析

  1. 利用桟来实现反转:时间复杂度O(N),空间复杂度O(N);
    将链表推入桟内,然后出桟构成新的链表;
  2. 原地反转,利用其他的一些变量来进行转换:时间复杂度O(N)空间复杂度O(1)。

代码实现

package algorithm_zuochengyun;

public class CH2_04_reverseList {

// 给定一个单向链表头结点head,将链表反转
public static Node reverseList(Node head) {
    Node pre = null;
    Node next = null;
    if (head == null || head.next == null) {
        return head;
    }
    while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

public static Node getReverseListFirst(Node head, int n) {
    // 假设123456789 从1翻转到5即可得 543216789
    // 此方法返回5这个结点,node(1).next = null;
    Node pre = null;
    Node next = null;
    if (head == null || head.next == null) {
        return head;
    }
    while (n-- > 0) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

public static Node getReverseListRest_First(Node head, int n) {
    // 假设123456789 从1翻转到5即可得 543216789
    // 此方法返回6这个结点
    Node pre = null;
    Node next = null;
    if (head == null || head.next == null) {
        return head;
    }
    while (n-- > 0) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return next;
}

public static DoubleNode reverseList(DoubleNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    DoubleNode last = null;
    DoubleNode next = null;
    DoubleNode cur = head;
    DoubleNode temp = null;
    while (cur != null) {
        next = cur.next;
        cur.next = last;
        last = cur.last;
        cur.last = next;
        last = cur;
        cur = next;

    }
    return last;
}

public static void main(String[] args) {
    Node head = Node.init();
    Node.Print(head);
    // Node.Print(reverseList(head));
    Node.Print(getReverseListFirst(head, 7));

    DoubleNode head1 = DoubleNode.init();
    DoubleNode.PrintNext(head1);
    DoubleNode.PrintNext(reverseList(head1));

}

}

实现结果

这里写图片描述

这里写图片描述

问题总结

题目不难,要利用已经有的结构来进行完善;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值