24. 两两交换链表中的节点
题目链接:24. 两两交换链表中的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//递归法
//终止条件:链表只剩一个节点或者没有节点,没得交换了。
//返回值:已经处理好的链表
if(head==null||head.next==null){
return head;
}
//将链表看为三部分:head,head.next,swapPairs(next.next)
//交换head和head.next
ListNode next = head.next;
//head连接swapPairs(next.next)
head.next=swapPairs(next.next);
//next连接head
next.next=head;
//根据第二步:返回给上一级的是当前已经完成交换,处理好的节点。
return next;
}
}
19.删除链表的倒数第N个节点
题目链接:19.删除链表的倒数第N个节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//双指针法
//倒数n转换为快慢指针的差值
ListNode dummyNode = new ListNode();
ListNode fastNode = new ListNode();
ListNode slowNode = new ListNode();
dummyNode.next=head;
fastNode=dummyNode;
slowNode=dummyNode;
for(int i =0;i<=n;i++){
fastNode=fastNode.next;
}
while(fastNode!=null){
slowNode=slowNode.next;
fastNode=fastNode.next;
}
slowNode.next=slowNode.next.next;
return dummyNode.next;
}
}
面试题 02.07. 链表相交
题目链接:面试题 02.07. 链表相交
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//理解题目,转换思维
ListNode curA = headA;
ListNode curB = headB;
int lenA =0,lenB=0;
while(curA!=null){
curA=curA.next;
lenA++;
}
while(curB!=null){
curB=curB.next;
lenB++;
}
curA=headA;
curB=headB;
//让curA为最长链表的头,LenA为其长度
if(lenB>lenA){
//swap(lenA,lenB)
int temp = lenA;
lenA=lenB;
lenB=temp;
//swap(curA,curB)
ListNode tempNode=curA;
curA=curB;
curB=tempNode;
}
//求长度差
int gap = lenA-lenB;
//让curA和curB在同一起点(末尾位置对齐)
while(gap--!=0){
curA=curA.next;
}
//遍历curA和curB,遇到相同的直接返回
while(curA!=null){
if(curA==curB){
return curA;
}
curA=curA.next;
curB=curB.next;
}
return null;
}
}
142.环形链表II
题目链接:142.环形链表II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
//记得结论先,证明不是很明白
ListNode fast = head;
ListNode slow = 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;
}
}