代码随想录算法训练营第四天| 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();
}
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;
}
}
}