力扣24.两两交换链表中的节点
链接: link
思路
这道题不是单纯的交换两个节点的值,而是节点之间的交换。
这道题设置一个虚拟节点指向头节点head会比较容易,
第一步:让虚拟节点指向第二个节点;
第二步:第二个节点指向第一个节点;
第三步:第一个节点指向第二个节点的后继;
涉及到的变量有:
1.虚拟节点
2.第一个节点
3.第二个节点
4.临时节点,指向下一轮的第一个节点
5.当前节点
解:
/**
* 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 tempHead = new ListNode(-1); // 虚拟头节点
tempHead.next = head;
ListNode temp; // 保留交换两个节点后的节点
ListNode cur = tempHead;
ListNode first; // 第一个节点
ListNode second;// 第二个节点
while (cur.next != null && cur.next.next != null) {
temp = cur.next.next.next; // 下一轮需要换的节点
first = cur.next;
second = cur.next.next;
cur.next = second;
second.next = first;
first.next = temp;
cur = first;// cur 移动 下一轮交换做准备
}
return tempHead.next;
}
}
19.删除链表的倒数第N个节点
链接: link
/**
* 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 tempHead = new ListNode(-1);
tempHead.next = head;
ListNode fast = tempHead;
ListNode slow = tempHead;
// fast 指针先移动n+1次
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
// slow fast同时移动,当fast指向null时停止,此时删除slow指向节点的下一个节点
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
// 删除节点
if (slow.next != null) {
slow.next = slow.next.next;
}
return tempHead.next;
}
}