剑指 Offer 24. 反转链表(Java、栈、递归、迭代)

原题地址

剑指 Offer 24. 反转链表

题目描述

在这里插入图片描述

题目思路

方法一:辅助栈

  • 利用栈先入后出的特点,依次将链表元素入栈,再从中弹出连接为新链表。

方法二:递归法

  • 利用递归思想,先访问至链表末端,从末端开始往前连接。

方法三:迭代法

  • 依次遍历链表,修改指向。

代码实现

使用到的方法

  1. pop():移除堆栈顶部的对象,并作为此函数的值返回该对象。
  2. push():把项压入堆栈顶部。
  3. empty():判断是否为空栈。

辅助栈法

class Solution {

    //栈
    private Stack<ListNode> stack = new Stack<ListNode>();
    private ListNode virNode = new ListNode();//虚拟头节点
    private ListNode curNode = new ListNode();//模拟当前节点

    public ListNode reverseList(ListNode head) {

        if(head == null){
            return null;
        }

        while(head != null){
            stack.push(head);
            head = head.next;
        }
        
        virNode.next = stack.pop();
        curNode = virNode.next;
        
        while(!stack.empty()){
            curNode.next = stack.pop();
            curNode = curNode.next;
        }
        curNode.next = null;

        return virNode.next;
    }
}

递归法

class Solution {
    ListNode virNode = new ListNode();
    public ListNode reverseList(ListNode head) {
        recur(head,null);
        return virNode.next;
    }

    void recur(ListNode curNode, ListNode preNode){
        if(curNode == null) {
            virNode.next = preNode;
            return;
        }
        recur(curNode.next,curNode);
        curNode.next = preNode;
    }
}

迭代法

class Solution {

    ListNode pre = null;
    ListNode next = null;

    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        while(head != null){
        //需要先保存下一节点,再修改当前节点的next
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        return pre;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值