**Leetcode(24)两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
//创建一个虚拟头节点---可以避免头节点为空的情况出现
ListNode dummyHeadNode=new ListNode(0);
dummyHeadNode.next=head;
ListNode currentNode=dummyHeadNode;
//判断结束条件--------判断奇数和偶数条件,只要有一个为假,则结束遍历
while (currentNode.next!=null&¤tNode.next.next!=null) {
ListNode temp1=currentNode.next;
ListNode temp2=currentNode.next.next;
currentNode.next.next=currentNode.next.next.next;//节点位置已经改变了,不能再用currentNode指向之前的元素了;1-3
//temp2.next=currentNode.next;//2-1这样也行
temp2.next=temp1;
currentNode.next=temp2;//从后往前来,头到2//提前保存变量
currentNode=currentNode.next.next;
}
return dummyHeadNode.next;//创建虚拟节点后要经历下一个变化
}
}
Leetcode(19)删除链表的倒数第 N 个结点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHeadNode=new ListNode(-1);
dummyHeadNode.next=head;
ListNode currentNode=dummyHeadNode;
int count=0;
while (currentNode.next!=null) {
currentNode=currentNode.next;
count++;//数出来即为链表的长度
}
int index=count-n;//此时转化为删除第几个元素
currentNode=dummyHeadNode;
for (int i = 0; i < index; i++) {
currentNode=currentNode.next;
}
currentNode.next=currentNode.next.next;
return dummyHeadNode.next;
}
}
Leetcode(160)相交链表
ListNode currentNodeA=headA;
ListNode currentNodeB=headB;
//求A、B链表的长度
int lenA=1;
int lenB=1;
while (currentNodeA!=null) {
currentNodeA=currentNodeA.next;
lenA++;
}
while (currentNodeB!=null){
currentNodeB=currentNodeB.next;
lenB++;
}
//链表A、B长度求出来后
if(lenA>lenB){
int lnABTemp=lenA-lenB;
for (int i = 0; i <lnABTemp ; i++) {
currentNodeA=currentNodeA.next;
}
for(int j=0;j<lenB;j++){
if(currentNodeA.val==currentNodeB.val){
return currentNodeA;
}
currentNodeA=currentNodeA.next;
currentNodeB=currentNodeB.next;
}
return null;
}else if(lenB>lenA){
int lnBATemp=lenB-lenA;
for (int i = 0; i < lnBATemp; i++) {
currentNodeB=currentNodeB.next;
}
for (int j = 0; j < lenA; j++) {
if(currentNodeB.val==currentNodeA.val){
return currentNodeB;
}
currentNodeA=currentNodeA.next;
currentNodeB=currentNodeB.next;
}
return null;
}else{
for (int i = 0; i < lenA; i++) {
if(currentNodeB.val==currentNodeA.val){
return currentNodeB;
}
currentNodeA=currentNodeA.next;
currentNodeB=currentNodeB.next;
}
return null;
}
}
LeetCode(142)环形链表 II**
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fastNode=head;
ListNode slowNode=head;
while (fastNode!=null&&fastNode.next!=null) {//空指针异常问题
slowNode=slowNode.next;//得往后走
fastNode=fastNode.next.next; //让它们先动起来
if(fastNode==slowNode){
//说明有环
ListNode index1=fastNode;
ListNode index2=head;
while(index1!=index2){
index1=index1.next;
index2=index2.next;
}
return index1;
}
}
return null;
}
}