Java 剑指-15 leetcode-206 反转链表

题目描述

对给定的单链表进行反转。

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

    public void reverse(){
        1.定义多个指针
        Node prev = null;
        Node cur = this.head;
        Node newHead = null;  //创建空结点为了方便表示反转后的表头
        //遍历单链表
        while(cur != null){
            //curNext指向当前结点的引用所指向的对象,代表下一次反转的结点对象
            Node curNext = cur.next;  
            if(curNext == null){
                newHead = cur;  //此时新的表头指向cur,此时cur为尾结点
            }
            cur.next = prev;  //cur的引用指向空结点
            prev = cur;  //prev指向cur所指向的对象
            cur = curNext;  //cur指向curNext所指向的对象
        }
        //原来的表头成了反转后的尾结点,因而需要重新指定表头,否则只打印了一个元素        
        this.head = newHead; 
    }


    2.类似头插法
    public void reverse1(){
        Node prev = null;
        while(this.head != null){
            Node cur = this.head;
            this.head = this.head.next;
            cur.next = prev;
            prev = cur;
        }
        this.head = prev;
    }

    3.类似头插法
    public Node reverse2(){
        Node prev = null;
        Node cur = this.head;
        while(cur != null){
            Node curNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur =curNext;
        }
        return prev;  //链表新的头结点
    }

真心觉得链表题思路不好用文字表达,代码注释清楚比啥都强。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值