代码随想录算法训练营第四天| 24. 两两交换链表中的节点、19.删除链表的倒数第N个节点、160. 链表相交 142.环形链表II(Java)

代码随想录算法训练营第四天| 24. 两两交换链表中的节点、19.删除链表的倒数第N个节点、160. 链表相交 142.环形链表II(Java)

24 两两交换链表中的节点

  
package com.shuzijun.leetcode.editor.en;
public class SwapNodesInPairs{
      public static void main(String[] args) {
           Solution solution = new SwapNodesInPairs().new Solution();
      }
      //leetcode submit region begin(Prohibit modification and deletion)


//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) {
        //定义一个虚拟头结点,方便返回链表
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next=head;
        ListNode cur = dummyHead;
        //存储每次位移后的游标的上一个和下一个元素
        ListNode temp = null;
        ListNode temp1 = null;
        while(cur.next!=null && cur.next.next!=null){
            //存储游标移动后的上一个元素
            temp=cur.next;
            //存储游标移动后的下一个元素
            temp1=cur.next.next.next;
            //让头结点指向游标移动后的位置
            cur.next=cur.next.next;
            //反转位移内的2个元素
            cur.next.next=temp;
            //重新关联上链
            cur.next.next.next=temp1;

            cur=cur.next.next;
        }

        return dummyHead.next;
    }
}

  }

19 删除链表的倒数第N个节点

package com.shuzijun.leetcode.editor.en;
public class RemoveNthNodeFromEndOfList{
      public static void main(String[] args) {
           Solution solution = new RemoveNthNodeFromEndOfList().new Solution();
      }
      //leetcode submit region begin(Prohibit modification and deletion)


// 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 dummyNode= new ListNode(-1);
        dummyNode.next=head;
        ListNode slow_cur = dummyNode;
        ListNode fast_cur = dummyNode;
        ListNode temp =null;
        int k=0;
        while (fast_cur!=null){
            if(k>n){

                slow_cur=slow_cur.next;
            }
            fast_cur=fast_cur.next;
            k++;
        }

        slow_cur.next=slow_cur.next.next;

        return  dummyNode.next;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值