题目一 24. 两两交换链表中的节点 - 力扣(LeetCode)
问题
- 指针应该指向哪里才能操作要交换的两个节点?
答:cur指向dummy,才能操作头节点和下一个节点 - 遍历终止条件是什么?
答:cur.next != null && cur.next.next != null - next交换顺序(一定要画图)
- 更新cur,cur指向交换2节点的前一个
tmp = cur.next; .... cur = tmp;
代码
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null) {
return null;
}
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null) {
// 交换顺序
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = tmp.next.next;
cur.next.next = tmp;
cur = tmp;
}
return dummy.ne
}
}
题目二 19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
注意:n的有效性已经保证了
代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
// 计算链表总长度
int sz = 0;
while(cur.next != null){
cur = cur.next;
sz++;
}
// cur归位到虚拟头节点
cur = dummy;
// 计算删除第几个节点,从0开始
int index = sz - n;
while(index > 0){
cur = cur.next;
index--;
}
// cur指向要删除节点的前一个
cur.next = cur.next.next;
return dummy.next;
}
}
题目三 142. 环形链表 II - 力扣(LeetCode)
思路
- 怎么判断是否有环
- fast指针走2步,slow指针走1步,如果fast和slow相遇,说明有环
- 循环终止条件????
- 快指针走在前面,只需要判断快指针合法
- 怎么找到环的入口
- 在相遇位置定义index2,链表开头位置定义index1,二者同时向后遍历,index1=index2的位置为环的入口
代码
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
// int pos = -1;
ListNode index1 = head;
ListNode index2;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
// pos = 0;
index2 = slow;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index2;
}
}
return null;
}
}