24.两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题思路
很麻烦的一道题目,不是很理解。还是看视频+文章才AC的。
解法1
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
ListNode tmp;
ListNode firstNode;
ListNode secondNode;
while (cur.next != null && cur.next.next != null) {
tmp = cur.next.next.next;
firstNode = cur.next;
secondNode = cur.next.next;
secondNode.next = firstNode;
firstNode.next = tmp;
cur = firstNode;
}
return dummy.next;
}
19.删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
解题思路
很简单,因为之前刷过类似的题目,所以第一次就AC了。
解法1
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
if (slow.next != null) {
slow.next = slow.next.next;
}
return dummy.next;
}
面试题 02.07. 链表相交
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
解题思路
我之前自己写的时候,就是卡尔的第二种思想。我觉得第一种太复杂了,还是掌握第二个算法就好。
解法1
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1 = headA;
ListNode p2 = headB;
while (p1 != p2) {
if (p1 == null) {
p1 = headB;
} else {
p1 = p1.next;
}
if (p2 == null) {
p2 = headA;
} else {
p2 = p2.next;
}
}
return p1;
}
142.环形链表II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
解题思路
很经典的一道题目,因为练得很多次,因此没啥难度。
解法1
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = 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;
}