19. 删除链表的倒数第 N 个结点
思路
快慢指针
1.快指针从头节点要先走n-1步,
2.慢指针再从头节点出发,直到fast指针为空,
3.此时slow指针指向倒数N+1个节点
4.根据倒数N+1个节点删除倒数N+1个节点
注意:设置哑节点可以避免头节点的讨论
代码
/**
* 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 temp = new ListNode();
temp.next = head;
ListNode fast = temp;
while(n >= 0 && fast != null){
fast= fast.next;
n--;
}
ListNode slow = temp;
while(fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return temp.next;
}
}
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) {
if(head == null || head.next == null){
return head;
}
ListNode dump = new ListNode();
dump.next = head;
ListNode cur = dump;
while(cur.next != null && cur.next.next != null){
ListNode curNext = cur.next;
ListNode curNextNext = cur.next.next;
ListNode curNextNextNext = curNextNext.next;
cur.next = curNextNext;
curNextNext.next = curNext;
curNext.next = curNextNextNext;
cur = curNext;
}
return dump.next;
}
}
递归解法
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/swap-nodes-in-pairs/solutions/444474/liang-liang-jiao-huan-lian-biao-zhong-de-jie-di-91/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
面试题 02.07. 链表相交
思路
双指针寻找相交节点,(null节点也视为相交的一种)
思路代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode cur1 = headA;
ListNode cur2 = headB;
while(cur1 != cur2){
cur1 = (cur1 == null) ? headB:cur1.next;
cur2 = (cur2 == null) ? headA:cur2.next;
}
return cur1;
}
}
142. 环形链表 II
思路代码
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null ){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}