24. 两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode vrNode = new ListNode(0);
vrNode.next = head;
ListNode fistNode; //临时节点 初始两个交换的第一个节点
ListNode secondNode; //临时节点 初始两个交换的第二个节点
ListNode temp; //暂存节点 用暂存等待交换的第一个节点
ListNode cur = vrNode;
while(cur.next != null && cur.next.next != null){
temp = cur.next.next.next;
fistNode = cur.next;
secondNode = cur.next.next;
cur.next = secondNode; //步骤一
secondNode.next = fistNode; //步骤二
fistNode.next = temp; //步骤三
cur = fistNode; //cur进行移动 下一次交换的前一个节点
}
return vrNode.next;
}
}
19. 删除链表的倒数第N个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//双指针的经典应用,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
//设置了虚拟头节点需要走n+1步,直到fast为null
ListNode vrNode = new ListNode(0);
vrNode.next = head;
ListNode slowIndex = vrNode;
ListNode fastIndex = vrNode;
//fast指针先走n+1步
for(int i=0; i <= n ;i++){
fastIndex = fastIndex.next;
}
//fast slow指针同时走 直到fast为null时 slow指针为删除目标指针前一个节点
while(fastIndex != null){
fastIndex = fastIndex.next;
slowIndex = slowIndex.next;
}
slowIndex.next = slowIndex.next.next;
return vrNode.next;
}
}
160. 相交链表
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//先分别求出两个链表的长度
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0;
int lenB = 0;
while(curA!=null){
lenA++;
curA = curA.next;
}
while(curB!=null){
lenB++;
curB = curB.next;
}
//重置节点 之前节点已经遍历到末尾
curA = headA;
curB = headB;
//计算两个链表长度的差值 让A链表为长的 如果短就将B赋给A
if(lenB > lenA){
int lenTemp = lenA;
lenA = lenB;
lenB = lenTemp;
ListNode temp = curA;
curA = curB;
curB = temp;
}
int gap = lenA - lenB;
while(gap-- > 0){
curA = curA.next;
}
//使得链表指针移动到同一位置 看是否为同一指针
while(curA != null){
if(curA == curB){
return curA;
}
//不是一起则移动
curA = curA.next;
curB = curB.next;
}
return curA;
}
}
142. 环形链表
public class Solution {
public ListNode detectCycle(ListNode head) {
//判断如何有环
//快慢指针 从头节点出发 fast指针走两步 慢指针走一步 如果相遇就证明有环
//如果有环如何找到这个环的入口
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){ //有环
//当相遇后从头节点再出发一个节点 相遇节点出发一个节点 两个节点相遇就为环入口
ListNode index1 = head;
ListNode index2 = fast;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}