24. 两两交换链表中的节点
使用虚拟头节点比较方便,在两两交换的过程钟,关键是要提前保存接下去需要指向的两个节点,还有结束后移动两个节点,最好画图。
/**
* 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) {
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
ListNode cur = dummyhead;
//保证接下来两个节点不为空
while(cur.next != null && cur.next.next != null){
//保存两个临时节点
ListNode tmp1 = cur.next;
ListNode tmp2 = cur.next.next.next;
//开始改变方向
cur.next = cur.next.next;
cur.next.next = tmp1;
cur.next.next.next = tmp2;
//再移动两个节点
cur = cur.next.next;
}
return dummyhead.next;
}
}
19. 删除链表的倒数第 N 个结点
关键是能想到第一个指针走n+1步
/**
* 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 fast = dummy;
ListNode slow = dummy;
//fast提前走n步
while(n -- > 0 && fast != null){
fast = fast.next;
}
//多走一步,保证slow指向删除节点的上一个节点
fast = fast.next;
while(fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}