一、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) {
// base case 退出提交
if(head == null || head.next == null) return head;
// 获取当前节点的下一个节点
ListNode next = head.next;
// 进行递归
ListNode newNode = swapPairs(next.next);
// 这里进行交换
next.next = head;
head.next = newNode;
return next;
}
}
二、19.删除链表的倒数第N个节点
思路:
使用双指针的思路,定义快慢指针,先让快指针走n步,然后快慢指针同时向后移动,一直到,快指针指向链表的尾部,此时,因为快指针比慢指针多走n步,慢指针此时所指的就是在链表的倒数第n-1个节点,只需要跳过下一个节点就可以了。
代码:
/**
* 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) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode slow = dummyNode;
ListNode fast = dummyNode;
//先让快指针走n步
for(int i = 0 ;i<n;i++){
fast = fast.next;
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
}
三、面试题 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){//求链表A的长度
lenA ++;
curA = curA.next;
}
while (curB != null) { // 求链表B的长度
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
//让链表A称为长度最长的链表
if(lenB>lenA){
//交换长度
int temp = lenA;
lenA = lenB;
lenB = temp;
//交换链表
ListNode temp1 = curA;
curA = curB;
curB = temp1;
}
//求长度差
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 null;
}
}
四、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(fast == slow ){
ListNode index1 = fast ;
ListNode index2 = head;
while(index1!=index2){
index2 = index2.next;
index1 = index1.next;
}
return index1;
}
}
return null;
}
}