24. 两两交换链表中的节点
一定要注意空指针异常
public ListNode swapPairs(ListNode head) {
if (head == null)
return head;
ListNode dummy_head = new ListNode(-1);
dummy_head.next = head;
ListNode p = dummy_head;
ListNode f = head;
ListNode s = null;
while (f != null && f.next != null) {
s = f.next;
f.next = s.next;
s.next = f;
p.next = s;
p = f;
f = f.next;
}
return dummy_head.next;
}
19. 删除链表的倒数第 N 个结点
运用快慢指针
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || head.next == null)
return null;
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode fast = dummyHead;
ListNode slow = dummyHead;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}