编程导航算法通关村第二关|青铜挑战—手写反转链表

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

使用栈实现

 public ListNode reverseList(ListNode head) {
      if (head == null || head.next == null) return head;
        Stack stack = new Stack();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        ListNode newNode = (ListNode) stack.pop();
        ListNode curNewNode = newNode;
        //这里对栈进行反转操作
        while (stack.size() != 0) {
            ListNode data = (ListNode) stack.pop();
            curNewNode.next = data;
            curNewNode = curNewNode.next;
        }
        curNewNode.next = null;
        return newNode;
    }

循环实现

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

        while(head != null) {
            //记录后面的节点
            ListNode cur = head.next;
            //把head指向空,也就是newNode
            head.next = newNode;
            //再把newHead = head,这样是为了在下一次循环中后面的节点可以指向前面的节点
            newNode = head;
            //最后把head指向cur即可
            head = cur;
        }
     return newNode;
    }

递归实现

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

         ListNode linked = reverseList(head.next);
         //这里会拿到倒数第二个节点
         head.next.next = head;
         head.next = null;
         return linked;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值