24. 两两交换链表中的节点
思路:
采用递归的方法
在递归时,一定要注意
1,终止条件
2,返回值
3,具体操作
/**
* 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;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
19.删除链表的倒数第N个节点
思路:
使用快慢指针,来定位倒数第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) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode slow = dummyHead, quick = dummyHead;
for(int i = 0; i < n+1 ; i++){
quick = quick.next;
}
while(quick != null){
slow = slow.next;
quick = quick.next;
}
slow.next = slow.next.next;
return dummyHead.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) {
int lengthA = 0, lengthB = 0;
ListNode tempA = headA, tempB = headB;
//遍历链表A,得到链表A的长度
while(tempA != null){
lengthA++;
tempA = tempA.next;
}
//遍历链表B,得到链表B的长度
while(tempB != null){
lengthB++;
tempB = tempB.next;
}
tempA = headA;
tempB = headB;
//将较长的链表指针指向和较短的链表相等的位置
if(lengthB > lengthA){
int temp = lengthA;
lengthA = lengthB;
lengthB = temp;
ListNode tempNode = tempA;
tempA = tempB;
tempB = tempNode;
}
//现在链表A一定比链表B长了
int gap = lengthA - lengthB;
while(gap != 0){
tempA = tempA.next;
gap--;
}
//比较两个指针是否相等,不想等向后挪
while(tempA != null){
if(tempA == tempB){
return tempA;
}
tempA = tempA.next;
tempB = tempB.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, slow = head;
while(true){
if(fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
if(fast == slow) break;
}
fast = head;
while(slow != fast){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}