• 剑指Offer-15:反转链表


    题目描述

    输入一个链表,反转链表后,输出新链表的表头。例如链表为1->2->3->4 反转后为1<-2-<3-<4

    节点定义如下:

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

    思路一:

    利用三个指针是实现链表反转

    public class Solution {
        public ListNode ReverseList(ListNode head) {
             // 判断链表为空
            if(head == null ){
                return null;
            }
            ListNode pre = null; // 当前节点的前一个节点,也就是新链表的头结点
            ListNode next = null; // 当前节点的下一个节点
            while( head != null){
                next = head.next; // 记录当前节点的下一个节点位置;
                head.next = pre; // 让当前节点指向前一个节点位置,完成反转
                pre = head; // pre 往右走
                head = next;// 当前节点往右继续走
            }
            return pre;
        }
    }

    思路二:

    利用递归的思想,假设链表为1->2->3->4->5先迭代到链表末尾5,然后从5开始依次反转整个链表

    head.next.next = head;是指使当前节点的下一个节点指向自己
    head.next = null断开与下一个节点的联系,完成真正的反序操作

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head==null||head.next==null)    //链表为空时返回
                return head;
            ListNode reserveNode = ReverseList(head.next);    //循环到链表尾部
            head.next.next = head;//反转链表的指向
            head.next = null;//断开原head的指向防止错链
            return reserveNode;
        }
    }
  • 相关阅读:
    [git]使用Idea创建一个git项目
    [git]分支管理策略
    Restful 风格
    [spring boot]idea中实现热部署的方法
    [jquery]JSON.parse()与JSON.stringify()
    [spring mvc]<mvc: annotation-driven />的作用
    [spring mvc][转]<mvc:default-servlet-handler/>的作用
    [mybatis]传值和返回结果
    [spring]@Resource和@Autowired区别对比
    html流程实现
  • 原文地址:https://www.cnblogs.com/zengcongcong/p/11452856.html
Copyright © 2020-2023  润新知