24. 两两交换链表中的节点 Swap Nodes in Pairs - LeetCode
奇数节点最后一个就不换,偶数节点就刚好两两交换
cur指针要指向要反转的两个节点的前一个节点
dummy.next = head;
cur = dummy;
while (cur.next != null && cur.next.next != null)//偶数cur.next == null结束,奇数cur.next.next == null
ListNode tmp = cur.next;
ListNode tmp1 = cur.next.next;
cur.next = cur.next.next;
cur.next.next = tmp;
tmp.next = tmp1;
cur = cur.next.next;
return dummy.next;
/**
* 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) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode tmp = cur.next;
ListNode tmp1 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = tmp;
tmp.next = tmp1;
cur = cur.next.next;
}
return dummy.next;
}
}
19.删除链表的倒数第N个节点 Remove Nth Node From End of List - LeetCode
设一个快快和慢慢,快快比慢慢先走N步,知道快快.next== null
最后slow.next = slow.next.next来删除倒数第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) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
160.链表相交 Intersection of Two Linked Lists - LeetCode
/**
* 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 curA = headA;
ListNode curB = headB;
int lenA = 0;
int lenB = 0;
while (curA != null) {
lenA++;
curA = curA.next;
}
while (curB != null) {
lenB++;
curB = curB.next;
}
if (lenA > lenB) {
while (lenA != lenB) {
headA = headA.next;
lenA--;
}
} else {
while (lenA != lenB) {
headB = headB.next;
lenB--;
}
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
}
142.环形链表II Linked List Cycle II - LeetCode
/**
* 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;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) break;
}
if (fast == null || fast.next == null) return null;
while (head != slow) {
head = head.next;
slow = slow.next;
}
return head;
}
}