继续刷几道链表题目,主要还是链表那些基本操作,增删改查,虚拟头节点,快慢指针。
直接山题目如下:
24. 两两交换链表中的节点
//未加入虚节点
public ListNode swapPairs(ListNode head) {
if(head==null || (head!=null&&head.next==null)){
return head;
}
ListNode pre = head;
ListNode cur = pre.next;
ListNode res = cur;
ListNode aft = cur.next;
while(cur!=null &&pre!=null){
cur.next = pre;
pre.next=aft;
pre = aft;
// System.out.println(pre.val);
cur = pre.next;//空指针异常
aft = cur.next;
}
return res;
}
}
//正确做法,加入虚节点,且每个变量在while中初始化?需要注意,与之前反转链表对比
public ListNode swapPairs(ListNode head) {
if(head==null || (head!=null&&head.next==null)){
return head;
}
ListNode dumy = new ListNode(0,head);
ListNode cur = dumy;
ListNode first;
ListNode second;
while(cur!=null &&cur.next!=null&& cur.next.next!=null){
ListNode tmp = cur.next.next.next;
first = cur.next;
second = cur.next.next;
cur.next = second;
second.next=first;
first.next = tmp;
cur = first;
}
return dumy.next;
}
}
25. 删除链表的倒数第 N 个结点
看到题目我思维定势的认为用集合记录链表节点总数,然后遍历链表进行删除,发现很难做;
最后看了视频题解,知道用快慢指针后一下就实现了,还是要用笔在草稿纸上去理解,尤其最后一笔删除:
slow.next = slow.next.next;//不是slow.next = fast,一定要注意
public ListNode removeNthFromEnd(ListNode head, int n) {
// int count = 0;
// while(head!=null){
// count ++;
// head=head.next;
// }
// ListNode dumy = new ListNode(-1,head);
// ListNode cur = dumy;
// while(){
// }
if(head==null){
return head;
}
ListNode dumy = new ListNode(-1,head);
ListNode slow = dumy;
ListNode fast = dumy;
int i = 0;
while(i<n&&fast!=null){
fast = fast.next;
i++;
}
while(fast!=null&&fast.next!=null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;//不是slow.next = fast,一定要注意
return dumy.next;
}
142. 环形链表 II
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {// 有环
ListNode index1 = fast;
ListNode index2 = head;
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
总结:
链表常用快慢指针,注意是否加入虚节点助于题解。
链表的一大问题就是操作当前节点必须要找前一个节点才能操作。这就造成了,头结点的尴尬,因为头结点没有前一个节点了。
每次对应头结点的情况都要单独处理,所以使用虚拟头结点的技巧,