4-1.24题两两交换链表中的节点
题目
思路
考查链表操作
代码
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
ListNode cur = dummyhead;
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;
cur.next = secondnode; //步骤1
secondnode.next = firstnode; //步骤2
firstnode.next = tmp; //步骤3
cur = firstnode; //下一轮交换
}
return dummyhead.next;
}
}
总结
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)
4-2.19题删除链表的倒数第N个节点
题目
思路
考查链表的删除操作
代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
ListNode fast = dummyhead;
ListNode slow = dummyhead;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast= fast.next;
slow = slow.next;
}
//slow所指的位置就是待删除元素的前一个位置
slow.next = slow.next.next;
return dummyhead.next;
}
}
总结
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)
4-3.160题相交链表
题目
思路
值相同不代表链表相交
代码
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;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
//1. swap (lenA, lenB);
int tmpLen = lenA;
lenA = lenB;
lenB = tmpLen;
//2. swap (curA, curB);
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
// 求长度差
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;
}
}
总结
时间复杂度 :
O
(
n
+
m
)
O(n+m)
O(n+m)
空间复杂度 :
O
(
1
)
O(1)
O(1)
4-4.142题环形链表II
题目
思路
一是判断链表是否有环
二是找到环内入口
代码
public class Solution {
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 indexhead = head;
ListNode indexmeet = slow;
while (indexhead != indexmeet) {
indexhead =indexhead.next;
indexmeet = indexmeet.next;
}
return indexmeet;
}
}
return null;
}
}
总结
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)
链表总结
• 虚拟头节点YYDS
• 链表的基本操作
• 反转链表
• 相交链表
• 环形链表