反转链表【递归】

今天复习递归的时候遇见了一个大家都觉得很简单的题:反转链表

把自己别住了 想明白了觉得说这题用了这么久真的好丢人。。。。。。

详细的写下来,如果下次遇见再不会 我就打死我自己。。。。

题目:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

 先把节点写出来

public class Node {
      int val;
      Node next;
      Node() {}
      Node(int val) { this.val = val; }
      Node(int val, ListNode next) { this.val = val; this.next = next; }
  }

方法一:将头结点指向null; 变成最后一个结点;提前把第2保存在temp中。第二个结点指向第一个结点.....结束条件是cur=null

代码实现:  

    public Node reverseList(Node head) {
        Node temp;
        Node cur;
        Node pre;
        pre = null;
        cur = head;

        while
        (cur != null) {
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;

        }
        return pre;
    }

 

 

方法二:递归

找到结束递归的方法:当head或者head.next=null时,它的反转链表就是head  

用链表1,2,3,4举例:

public static Node reverseList2(Node head) {
        // 递归结束条件
        if (head == null || head.next == null) {
            return head;
        }
//第一次递归结束,返回的head=4;

        Node newList = reverseList2(head.next);//反转链表
         //返回上层递归 当head.next=3,传入reverseList2时head=3;
        head.next.next = head;
         //此时 head.next.next是4的下一个结点,那么把现在的head=3给head.next.next 即 
        (head.next.next = head) 
        //也就是说明4的下一个结点是3  
        head.next = null;

        //将3的下一个结点指向null  即将原来的3与4之间的连接断开
        return newList;
    }

画图理解更清晰

over

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值