剑指Offer第十五题:反转链表

剑指Offer第十五题:反转链表

在这里插入图片描述
输入一个链表,反转链表后,输出新链表的表头。

头插法

  1. 初始化:
    头结点pre = new ListNode(head);
    临时结点next,指向head的下一个结点

  2. 遍历链表,循环停止条件next == null
    2.1 先让head指向next结点 head = next
    2.2 先用临时结点存储下一个结点next = next.next
    2.3 进行反转,修改head.next,让head指向pre: head.next = pre;
    2.4 更新pre的位置 pre = head

  3. return pre

/*
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 head;
        }
        ListNode next = head.next;
        ListNode pre = new ListNode( head.val );
        while(next != null){
            head = next;
            next = next.next;
            head.next = pre;
            pre = head;
        }
        return pre;
    }
}

递归

例如A->B->C
当递归到C时return C,此时head是B B的next是C
所以B的next的next head.next.next = head 相当于C->B
再让head.next = null 相当于 C->B->null
返回 return C 相当于 C->B->null

此时倒数第二层递归中 head是A A的next是B
A的next的next head.next.next = head 相当于 B->A
再让 head.next = null B->A->null
返回 return C 相当于 C->B->A-null

    //递归
     public ListNode ReverseList(ListNode head) {
         if(head == null || head.next == null){
            return head;
         }
         ListNode temp = ReverseList(head.next);
         
         head.next.next = head;
         head.next = null;
         return temp;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值