24. 两两交换链表中的节点 19.删除链表的倒数第N个节点 面试题 02.07. 链表相交 142.环形链表II
文章目录
一、24. 两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
ListNode cur = head;
ListNode pre = new ListNode(-1);
ListNode begin = head.next;
pre.next = head;
while (cur != null && cur.next != null){
//交换节点
pre.next = cur.next;
ListNode temp = cur.next.next;
cur.next.next = cur;
cur.next = temp;
//进行下一轮交换
pre = cur;
cur = cur.next;
}
return begin;
}
}
二、19.删除链表的倒数第N个节点
1.引入库
代码如下(示例):双指针的操作,要注意,删除第N个节点,那么我们当前遍历的指针一定要指向 第N个节点的前一个节点。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre,cur;
ListNode dummpy = new ListNode(-1);
dummpy.next = head;
cur = dummpy;
pre = dummpy;
if (head == null) return head;
int i = 0;
while(cur.next != null && i < n){
cur = cur.next;
i++;
}
while (cur.next != null){
cur = cur.next;
pre = pre.next;
}
pre.next = pre.next.next;
return dummpy.next;
}
}
三、 面试题 02.07. 链表相交
代码如下(示例):依旧是使用双指针的思想。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
if (headA == headB) return headA;
int Alength = 1;
int Blength = 1;
ListNode curA = headA;
ListNode curB = headB;
while (curA.next != null){
Alength++;
curA= curA.next;
}
while (curB.next != null){
Blength++;
curB = curB.next;
}
int n = 0;
curA = headA;
curB = headB;
if (Alength >= Blength){
while (n < Alength - Blength){
curA = curA.next;
n++;
}
while (curA != null){
if (curA == curB) return curA;
curA = curA.next;
curB = curB.next;
}
}else{
while (n < Blength - Alength){
curB = curB.next;
n++;
}
while (curB != null){
if (curA == curB) return curA;
curA = curA.next;
curB = curB.next;
}
}
return null;
}
}
142.环形链表II
比较有难度,没有做出来。使用快慢指针来做。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode quick, slow;
quick = head;
slow = head;
while (quick != null && quick.next != null) {
slow = slow.next;
quick = quick.next.next;
//有环
if (slow == quick){
ListNode index1 = quick;
ListNode index2 = head;
while (index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index2;
}
}
return null;
}
}
总结
今天做题动手画了画,感觉思路清晰了很多。自己平时的学习方法可能不对。要多动手,多考虑。动手后只有最后一道题没有做出来,最后一道题还是之前的一个面试题,要深刻理解。