Java——反转链表

目录

反转链表Ⅰ 

题目

原地反转

原地反转的简化

取节点头插到新的链表

递归

反转部分链表

题目

图示思路

 


153a60f569a252298cf0c93da4bd01c8.gif

 

反转链表Ⅰ 

题目

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

示例 1:


输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

来源:力扣(LeetCode)
 

原地反转

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null){
            return null;//避免空指针异常
        }
        ListNode prev=null;
        ListNode cur=head;
        ListNode next=head.next;
        while(cur!=null){
            //翻转
            cur.next=prev;
            //迭代
            prev=cur;
            cur=next;
            if(next!=null)
                 next=next.next;

        }
        return prev;
    }
}

原地反转的简化

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}

取节点头插到新的链表

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head;
        ListNode newHead=null;
        while(cur!=null){
            ListNode next=cur.next;//借鉴原地反转,避免空指针异常的情况

            cur.next=newHead;
            newHead=cur;
            //迭代
            cur=next;

        }
        return newHead;


    }
}

递归

//这里写下递归
//结束条件:只有一个节点或者没有节点
//处理第一个结点与子链表翻转后的头节点
//返回最终的结点
//1(head)->2->3->null;
z//1(head)->{2<-3(newHead)};
//head->next->next=head;
//head->next=null;


class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

反转部分链表

题目

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
 

示例 1:


输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

来源:力扣(LeetCode)
 

图示思路

bcd52d8f643d40ef80d7f2e0dc31f20f.png 代码实现 

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        for(int i = 1; i < m; i++){
            pre = pre.next;
        }
        head = pre.next;
        for(int i = m; i < n; i++){
            ListNode nex = head.next;
            head.next = nex.next;
            nex.next = pre.next;
            pre.next = nex;
        }
        return dummy.next;
    }
}

 

 

 

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sqyaa.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值