- 两两交换链表中的节点 leetcode.com/problems/sw…
思路:这道题还是递归的做法是最简单的
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
// 获取当前节点的下一个节点,因为要返回的节点就是这个节点,这个节点相当于是新的头
ListNode nextNode = head.next;
// 递归函数返回的头节点
ListNode newNode = swapPairs(nextNode.next);
// 让新的头指向以前的头
nextNode.next = head;
// 以前的头指向右边递归函数返回的节点
head.next = newNode;
return nextNode;
}
}
理不清楚的可以看下这个视屏:www.bilibili.com/video/BV1Ka…
19.删除链表的倒数第N个节点 leetcode.com/problems/re…
思路:怎么找倒数第n个节点呢?用快慢指针,快指针先走n步,然后快慢指针同时移动,快指针到null,慢指针就到倒数第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) {
if (head == null) return head;
// 需要虚拟头节点来处理1个节点的情况
ListNode dummyHead = new ListNode(0,head);
ListNode fast = dummyHead;
ListNode slow = dummyHead;
// 移动快指针
while (n >= 0 && fast != null) {
fast = fast.next;
n--;
}
// 同时移动,直到fast移动到最后一个
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
if (slow.next != null) {
slow.next = slow.next.next;
}
return dummyHead.next;
}
}
160.链表相交 leetcode.com/problems/in…
思路:让两个指针在链表上同时移动,移动到尾了,就去另一条链表的头,这样如果有交叉点一定会相遇,因为链表长度不一样
/**
* 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 pA = headA;
ListNode pB = headB;
while (pA != pB) {
pA = (pA != null) ? pA.next : headB;
pB = (pB != null) ? pB.next : headA;
}
return pA;
}
}
142.环形链表II leetcode.com/problems/li… 思路:用两个快慢指针,一个走2步,一个走1步,如果有环,一定会相遇;然后再用一个指针从头开始走到和fast相遇的位置就是环的节点位置
/**
* 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) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// 如果相遇,把slow移动回头部
// 同时移动fast和slow
if (slow == fast) {
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}