算法训练营第四天

链表的相关知识:
力扣:24. 两两交换链表中的节点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {

    //    我的方法,有点复杂,定义了三个指针   pre,cur,temp
    //     ListNode cur =  new  ListNode();
    //     ListNode pre =  new  ListNode();
    //     ListNode dummyHead = new ListNode();
    //     ListNode temp = new ListNode();
    //     dummyHead.next = head;
    //     pre= dummyHead;
    //     if(head == null){
    //         return null;
    //     }
    //     cur = head;
    //     while(cur!= null && cur.next != null ){
    //         temp = cur.next.next;
    //         pre.next = cur.next;
    //         cur.next.next = cur;
    //         pre = cur;
    //         pre.next = temp;
    //         cur = temp;

    //     } 
    // return dummyHead.next;

    //代码随想录方法
    ListNode cur = new ListNode();
    ListNode temp = new ListNode();
    ListNode temp1 = new ListNode();
    ListNode dummyHead = new ListNode();
    dummyHead.next = head;
    cur = dummyHead;
    while(cur.next != null && cur.next.next != null){
        temp = cur.next.next.next;
        temp1 = cur.next;
        cur.next = cur.next.next;
        cur.next.next = temp1;
        cur.next.next.next = temp;
        cur = cur.next.next;
    }
    return dummyHead.next;
    }
}

总结:1.分析题目,为什么交换的是两两的节点?
如果是交换三个节点,方法是一样的吗?
2.我的方法和代码随想录的方法区别?
核心思想没变,都是用temp来储存中间的指针.
我的方法更复杂!

力扣:19.删除链表的倒数第N个节点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode();
        ListNode left = new ListNode();
        ListNode right = new ListNode();
         dummyHead.next = head;
         left = dummyHead;
         right = dummyHead;


         while(n>=0){
            right = right.next;
            n--;
        }
        // for(int i = 0;i <= n; i++){
        //     right = right.next;
        // }

         while(right != null){
            left = left.next;
            right = right.next;
         }

         left.next = left.next.next;
         return dummyHead.next;
    }
  
}

这道题思路就是双指针,但是要明白:
删除倒数第几个节点,那么左右指针的中间的间隔相差n个。那么right指针走n+1步。因为right节点的最终是最后节点的null;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值