链表逆序

链表逆序的思想:

    1)遍历链表中的节点,放入栈中,然后进行出栈的操作,即可得到逆序的链表;

    2)将链表中的元素,存入数组或者队列或者有序集合中,然后逆序去读元素,重新链接成链表;

    3)通过交换链表中的元素,从而实现逆序。可以这么理解——顺序移除链表中的头节点,作为头节点添加到新链表。即逐个遍历原链表中的节点,作为新链表的头节点,插入。

前两种方法比较简单,这里说下第三种方法。代码如下:

step1,构建节点

static class Node {
    private int value;
    private Node next;

    public Node(int value, Node next) {
        this.value = value;
        this.next = next;
    }

    public int getValue() {
        return value;
    }

    public Node setValue(int value) {
        this.value = value;
        return this;
    }

    public Node getNext() {
        return next;
    }

    public Node setNext(Node next) {
        this.next = next;
        return this;
    }

    public boolean hasNext() {
        return next != null;
    }
}

step2,初始化链表

/**
 * 构建一个链表
 *
 * @return 链表头节点
 */
private static Node initLink() {
    //头节点
    Node head = null;
    //当前节点
    Node cur = null;
    for (int i = 0; i < 10; i++) {
        if (cur == null) {
            cur = head = new Node(i, null);
            continue;
        }
        Node next = new Node(i, null);
        cur.setNext(next);
        cur = next;
    }
    return head;
}

step3,打印链表

/**
 * 遍历链表
 *
 * @param head head node
 */
private static void printLink(Node head) {
    Node node = head;
    while (node != null) {
        System.out.print(node.value + "->");
        node = node.next;
    }
    System.out.println();
}

step4,逆序

/**
 * 链表逆序
 *
 * @param headOld ori link head node
 * @return new link head node
 */
private static Node reverseLink(Node headOld) {
    Node head = headOld;
    Node next = head.next;
    while (next != null) {
        Node cur = next;
        next = next.next;

        if (head == headOld) {
            head.next = null;
        }
        cur.next = head;
        head = cur;
    }
    return head;
}

最后一步,运行

public static void main(String[] args) {
    System.out.println("初始化链表:");
    Node headOri = initLink();
    printLink(headOri);

    System.out.println("逆序后链表:");
    Node headNew = reverseLink(headOri);
    printLink(headNew);
    
    //打印结果
    //初始化链表:
    //0->1->2->3->4->5->6->7->8->9->
    //逆序后链表:
    //9->8->7->6->5->4->3->2->1->0->
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值