Leetcode刷题Day4----------------链表
1. 两两交换链表中的节点(24)
- 题目链接/文章讲解/视频讲解: https://programmercarl.com/0024.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.html
视频中的方法:
关键点:
- 开始的节点必须指向要反转的两个节点的前一个节点(虚拟头节点指向head)----> cur指向虚拟头节点,
- 循环判断条件:偶数(4)个节点,cur.next=null; 奇数(5)个节点,cur.next.next=null; 并且先写 cur.next=null; 因为如果第二个空了,直接就空指针异常了
- 循环内部步骤:
3.1 保存节点1
3.2 保存节点3
3.3 从虚拟头节点指向2
3.4 让2 (cur.next.next) 指向保存的1
3.5 让1(cur.next.next) 指向保存的3
3.6 cur 往后移动2个指针(3之前的) - 返回虚拟头节点的nxt
class Solution {public ListNode swapPairs(ListNode head) {ListNode dummy=new ListNode(-1,head);ListNode cur=dummy;while(cur.next!=null&&cur.next.next!=null){ListNode temp1=cur.next;ListNode temp3=cur.next.next.next;cur.next=cur.next.next;cur.next.next=temp1;cur.next.next.next=temp3;cur=cur.next.next;}return dummy.next;}
}
2. 删除链表的倒数第N个节点 (19)
- 题目链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
- 文章讲解/视频讲解:https://programmercarl.com/0019.%E5%88%A0%E9%99%A4%E9%93%BE%E8%A1%A8%E7%9A%84%E5%80%92%E6%95%B0%E7%AC%ACN%E4%B8%AA%E8%8A%82%E7%82%B9.html
方法:双指针,快指针定位到正数的n步,然后快慢指针一起相同速度运动,当快指针定位到末尾的时候,慢指针运动到的位置就是要删除的位置
class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {ListNode dummy=new ListNode(0,head);ListNode fast=dummy;ListNode slow=dummy;while(n-->0){//for(int i=0;ifast=fast.next;} while(fast.next!=null){slow=slow.next;fast=fast.next;}slow.next=slow.next.next;return dummy.next;}
}
3. 链表相交(面试题 02.07.)
- 题目链:
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/ - 文章讲解:https://programmercarl.com/%E9%9D%A2%E8%AF%95%E9%A2%9802.07.%E9%93%BE%E8%A1%A8%E7%9B%B8%E4%BA%A4.html
思路:
- 求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置
- 比较curA和curB是否相同,如果不相同,同时向后移动curA和curB,如果遇到curA == curB,则找到交点;否则循环退出返回空指针
4. 环形链表II(142)
- 题目链接/文章讲解/视频讲解:https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html
5. 链表总结