24. 两两交换链表中的节点
题目:24. 两两交换链表中的节点 - 力扣(LeetCode)
状态:AC,但比较慢
思路
关键条件:两两交换其中相邻的节点,不修改节点内部的值
注意:在纸上模拟下,画个图
代码
时间复杂度:O(n) 空间复杂度:O(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 swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
ListNode cur = head;
while (cur != null && cur.next != null) {
prev.next = cur.next;
ListNode temp = cur.next.next;
cur.next.next = cur;
cur.next = temp;
prev = cur;
cur = cur.next;
}
return dummy.next;
}
}
19.删除链表的倒数第N个节点
题目:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
状态:AC
思路
注意:优先快慢指针,两遍遍历的话第二次不要忘记将当前节点拉回头节点
代码
时间复杂度:O(n) 空间复杂度:O(1)
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy.next;
ListNode temp = dummy;
int count = 0;
while (cur != null) {
if (count >= n) {
temp = temp.next;
}
cur = cur.next;
count++;
}
temp.next = temp.next.next;
return dummy.next;
}
}
面试题 02.07. 链表相交
题目:面试题 02.07. 链表相交 - 力扣(LeetCode)
状态:只想到了哈希表的做法,题目还要理解下,不能只是对比节点的值
思路
注意:合并链表双指针法,是走完本链就切换到另一个链。
哈希表的做法更重要,另一个方法面试时不一定能推出来。
代码
时间复杂度:O(n) 空间复杂度:O(1)
// 哈希
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> visited = new HashSet<ListNode>();
ListNode temp = headA;
while (temp != null) {
visited.add(temp);
temp = temp.next;
}
temp = headB;
while (temp != null) {
if (visited.contains(temp)) {
return temp;
}
temp = temp.next;
}
return null;
}
}
// 双指针
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while(a != b){
if(a != null){
a = a.next;
}else{
a = headB;
}
if(b != null){
b = b.next;
}else{
b = headA;
}
}
return a;
}
}
142.环形链表II
题目:142. 环形链表 II - 力扣(LeetCode)
状态:半AC,用哈希表是会做的,计算规律的尽量会吧
思路
注意:相遇后不一定在环入口,还要再进行一轮判断
哈希表的做法更重要,另一个方法面试时不一定能推出来。
代码
时间复杂度:O(n) 空间复杂度:O(1)
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode fast = head;
ListNode low = head;
while(fast != null && fast.next != null){
low = low.next;
fast = fast.next.next;
if(low == fast){
ListNode index1 = fast;
ListNode index2 = head;
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}