24. 两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (pre.next != null && pre.next.next != null) {
ListNode n1 = pre.next;
ListNode n2 = n1.next;
pre.next = n2;
n1.next = n2.next;
n2.next = n1;
pre = n1;
}
return dummy.next;
}
}
19.删除链表的倒数第N个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
ListNode pre = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
if (fast == null) {
return null;
}
}
while (fast != null) {
pre = slow;
slow = slow.next;
fast = fast.next;
}
pre.next = slow.next;
return dummy.next;
}
}
面试题 02.07. 链表相交
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengthA = getListLength(headA);
int lengthB = getListLength(headB);
int difference = Math.abs(lengthA - lengthB);
ListNode nodeA = headA;
ListNode nodeB = headB;
if (lengthA > lengthB) {
for (int i = 0; i < difference; i++) {
nodeA = nodeA.next;
}
} else {
for (int i = 0; i < difference; i++) {
nodeB = nodeB.next;
}
}
while (nodeA != null && nodeB != null) {
if (nodeA == nodeB) {
return nodeA;
}
nodeA = nodeA.next;
nodeB = nodeB.next;
}
return null;
}
public int getListLength(ListNode head) {
if (head == null) {
return 0;
}
int res = 0;
ListNode cur = head;
while (cur != null) {
cur = cur.next;
res++;
}
return res;
}
}
142.环形链表II
看完思路之后写出来的代码,但是思路很灵活,不太好想
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while (true) {
if (fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}