力扣打卡day05

链表专项

反转题型
1.206. 反转链表(反转整个单链表)
方法一.双指针法

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head;
        ListNode pre=null;//pre指向cur的前一位
        ListNode temp=null;
        while(cur!=null){
            temp=cur.next;//保存cur的下一个节点
            cur.next=pre;
            pre=cur;
            cur=temp;
        }
        return pre;

    }
}

方法二.递归法

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

2.92. 反转链表 II(反转一部分链表)
方法一.递归

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(left==1){
            return reverseN(head,right);
        }
        head.next=reverseBetween(head.next,left-1,right-1);
        return head;
    }
    ListNode successor=null;
    public ListNode reverseN(ListNode head,int n){
        if(n==1){
            successor=head.next;
            return head;
        }
        ListNode last=reverseN(head.next,n-1);
        head.next.next=head;
        head.next=successor;
        return last;
    }
}

方法二.穿针引线

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode pre=dummy;
        for(int i=0;i<left-1;i++){
            pre=pre.next;
        }
        ListNode cur=pre.next;
        ListNode next;
        for(int i=left;i<right;i++){
            next=cur.next;
            cur.next=next.next;
            next.next=pre.next;
            pre.next=next;
            
        }
        return dummy.next;
    }
}

3.两两交换链表中的节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode cur=dummy;
        //针对偶数节点cur.next!=null,针对奇数节点cur.next.next!=null
        while(cur.next!=null&&cur.next.next!=null){
            ListNode temp=cur.next;
            ListNode temp1=cur.next.next.next;
            cur.next=cur.next.next;
            cur.next.next=temp;
            temp.next=temp1;
            cur=cur.next.next;
        }
        return dummy.next;

    }
}```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值