24. 两两交换链表中的节点
主要问题,以哪个时间段分手,不会导致节点丢了
p->1->2->3
- 先用一个temp找到1的手
- p去牵住2
- temp带着1去牵住3
- 2去牵住1
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode head_new = new ListNode(-1, head);
ListNode p = head_new;
while(p.next!=null && p.next.next!=null){
ListNode temp = p.next;
p.next = p.next.next;
temp.next = p.next.next;
p.next.next = temp;
p = temp;
}
return head_new.next;
}
}
递归
class Solution {
public ListNode swapPairs(ListNode head) {
//递归出口,要么没有节点,要么,只有一个节点
if(head == null || head.next == null) return head;
ListNode temp = head;
head = head.next;
temp.next =swapPairs(head.next) ;
head.next = temp;
return head;
}
}
19 删除链表的倒数第 N 个结点
遇到增加节点或者删除节点为了避免各种头尾判断,最好加一个next判断
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode new_head = new ListNode(-1, head);
ListNode slow = new_head;
ListNode fast = slow;
while(fast.next != null && n > 0){//防止n>size
n--;
fast = fast.next;
}
if(n > 0) return head;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return new_head.next;
}
}
160. 相交链表
不要想着太麻烦
ANULL BNULL 这个时结束,就代表不相交嘛
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode A = headA;
ListNode B = headB;
while(A!=B){
if(A == null){
A = headB;
}else A = A.next;
if(B == null){
B = headA;
}else B = B.next;
}
return A;
}
}
- 如果有环, fast走两步,slow走一步,两者一定会在环内相遇
- 相遇之后fast回头上,一步一步走,会在入口处遇到slow
追上时 2*(A+B) = A + (B+C)*k + C;
A = (B + C) *(k-1) + C;
意思就是A这段路 等于k-1个整环 加上C这段
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next;
slow = slow.next;
if(fast.next!=null) fast =fast.next;
if(fast == slow) break;
}
if(fast == null || fast.next == null) return null;
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next ==null) return head;
ListNode new_head = new ListNode(-1, head);
ListNode p = new_head;
ListNode tail = new_head;
int index = 0;
while(tail != null){
if(index!=0 && index % k == 0){
ListNode temp = tail.next;
ListNode cur_head = p.next;
p.next = reverse(cur_head, tail);
cur_head.next = temp;
p = cur_head;
tail = p;
}
index++;
tail = tail.next;
}
return new_head.next;
}
public ListNode reverse(ListNode head, ListNode tail){
tail.next = null;
ListNode p = head;
ListNode q = null;
while(head!=null){
p = head;
head = head.next;
p.next = q;
q = p;
}
return q;
}
}