leetcode 链表篇

leetcode 链表篇

链表篇

链表的java写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ListNode {
// 结点的值
int val;

// 下一个结点
ListNode next;

// 节点的构造函数(无参)
public ListNode() {
}

// 节点的构造函数(有一个参数)
public ListNode(int val) {
this.val = val;
}

// 节点的构造函数(有两个参数)
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}

一、移除链表元素

力扣题目链接

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例 1:

img

1
2
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

示例 2:

1
2
输入:head = [], val = 1
输出:[]

示例 3:

1
2
输入:head = [7,7,7,7], val = 7
输出:[]

提示:

  • 列表中的节点数目在范围 [0, 104]
  • 1 <= Node.val <= 50
  • 0 <= val <= 50
1
2
3
4
5
6
7
8
9
10
方法一:递归法
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null){
return null;
}
head.next = removeElements(head.next,val);
return head.val==val?head.next:head;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
方法二:迭代法
class Solution {
public ListNode removeElements(ListNode head, int val) {
// if (head == null){
// return null;
// }
// head.next = removeElements(head.next,val);
// return head.val==val?head.next:head;
ListNode dummyNode = new ListNode(val-1);
dummyNode.next = head;
ListNode tmp = dummyNode;
while (tmp.next != null){
if (tmp.next.val==val){
tmp.next = tmp.next.next;
}else{
tmp = tmp.next;
}
}
return dummyNode.next;
}
}

二、设计链表

力扣题目链接

你可以选择使用单链表或者双链表,设计并实现自己的链表。

单链表中的节点应该具备两个属性:valnextval 是当前节点的值,next 是指向下一个节点的指针/引用。

如果是双向链表,则还需要属性 prev 以指示链表中的上一个节点。假设链表中的所有节点下标从 0 开始。

实现 MyLinkedList 类:

  • MyLinkedList() 初始化 MyLinkedList 对象。
  • int get(int index) 获取链表中下标为 index 的节点的值。如果下标无效,则返回 -1
  • void addAtHead(int val) 将一个值为 val 的节点插入到链表中第一个元素之前。在插入完成后,新节点会成为链表的第一个节点。
  • void addAtTail(int val) 将一个值为 val 的节点追加到链表中作为链表的最后一个元素。
  • void addAtIndex(int index, int val) 将一个值为 val 的节点插入到链表中下标为 index 的节点之前。如果 index 等于链表的长度,那么该节点会被追加到链表的末尾。如果 index 比长度更大,该节点将 不会插入 到链表中。
  • void deleteAtIndex(int index) 如果下标有效,则删除链表中下标为 index 的节点。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
输入
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
输出
[null, null, null, null, 2, null, 3]

解释
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // 链表变为 1->2->3
myLinkedList.get(1); // 返回 2
myLinkedList.deleteAtIndex(1); // 现在,链表变为 1->3
myLinkedList.get(1); // 返回 3

提示:

  • 0 <= index, val <= 1000
  • 请不要使用内置的 LinkedList 库。
  • 调用 getaddAtHeadaddAtTailaddAtIndexdeleteAtIndex 的次数不超过 2000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class MyLinkedList {

ListNode head;
int size = 0;

private class ListNode {
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
}

public MyLinkedList() {
this.head = new ListNode(0);
this.size = 0;
}

public int get(int index) {
if(index<0||index>=size){
return -1;
}else{
ListNode currentNode = head;
for (int i=0;i<=index;i++){
currentNode = currentNode.next;
}
return currentNode.val;
}
}

public void addAtHead(int val) {
addAtIndex(0,val);

}

public void addAtTail(int val) {
addAtIndex(size,val);
}

public void addAtIndex(int index, int val) {
if (index > size) {
return;
}
if (index < 0) {
index =0;
}
size++;
ListNode currentNode = head;
ListNode pre = head;
ListNode addNode = new ListNode(val);
for(int i=0 ;i<=index;i++){
pre = currentNode;
currentNode = currentNode.next;
}
pre.next = addNode;
addNode.next = currentNode;
}

public void deleteAtIndex(int index) {
if (index<0||index>=size){
return;
}
size--;
ListNode currentNode = head;
for(int i=0;i<index;i++){
currentNode = currentNode.next;
}
if(currentNode.next!=null){
currentNode.next = currentNode.next.next;
}

}
}

/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/

三、翻转链表

力扣题目链接

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

img

1
2
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

img

1
2
输入:head = [1,2]
输出:[2,1]

示例 3:

1
2
输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1.双指针法:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cru = head;
ListNode tmp = null;
while (cru!=null){
tmp = cru.next;
cru.next = pre;
pre = cru;
cru = tmp;
}
return pre;
}
}

双指针法的代码很少,但其中的细节特别多,首先是初始化部分,cru为头节点,pre为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
递归的方法:
/**
* 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 reverseList(ListNode head) {
// 1.双指针
// ListNode pre = null;
// ListNode cru = head;
// ListNode tmp = null;
// while (cru!=null){
// tmp = cru.next;
// cru.next = pre;
// pre = cru;
// cru = tmp;

// }
// return pre;
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next =null;
return newHead;
}
}

不需要清楚递归的细节是怎么实现的,只需要知道它返回的链表已经是翻转结束的。
可以这么理解:1 -> 2 <-3 <- 4 <- 5: 2 3 4 5已经翻转完成,但1的next依然是指向2的,只要让2的next指向1,1再指向null就完成了。

四、两两交换链表中的节点

力扣题目链接

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

img

1
2
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

1
2
输入:head = []
输出:[]

示例 3:

1
2
输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
方法一:递归法,时间复杂度是On 空间复杂度也是On
/**
* 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){
return null;
}
if(head.next == null){
return head;
}
ListNode part = swapPairs(head.next.next);

ListNode second = head.next;
second.next = head;
head.next = part;
// 返回新的头节点,即原来的第二个节点
return second;

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
方法二:模拟法
/**
* 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 temp ; //用于记录第三个节点后的内容
ListNode dumyhead = new ListNode();//虚拟头节点
dumyhead.next = head;
ListNode cul = dumyhead;
ListNode firstnode ;
ListNode secondnode;
while(cul.next!=null&&cul.next.next!=null){
firstnode = cul.next;
secondnode = cul.next.next;
temp = cul.next.next.next;
cul.next = secondnode;
secondnode.next = firstnode;
firstnode.next = temp;
cul = firstnode;
}
return dumyhead.next;
}
}

五、删除链表的倒数第N个节点

力扣题目链接

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:

img

1
2
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:

1
2
输入:head = [1], n = 1
输出:[]

示例 3:

1
2
输入:head = [1,2], n = 1
输出:[1]

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

进阶:你能尝试使用一趟扫描实现吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fastIndex ;
ListNode slowIndex = new ListNode();
fastIndex = head;
slowIndex.next = head;
ListNode cur = slowIndex;

for (int i = 1 ;i <= n ;i++){
fastIndex = fastIndex.next;
}
while(fastIndex !=null){
fastIndex = fastIndex.next;
slowIndex = slowIndex.next;
}
slowIndex.next = slowIndex.next.next;
return cur.next;
}
}

六、链表相交

力扣题目链接

给你两个单链表的头节点 headAheadB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null

图示两个链表在节点 c1 开始相交

img

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构

示例 1:

img

1
2
3
4
5
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

示例 2:

img

1
2
3
4
5
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Intersected at '2'
解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

示例 3:

img

1
2
3
4
5
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。
由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
这两个链表不相交,因此返回 null 。

提示:

  • listA 中节点数目为 m
  • listB 中节点数目为 n
  • 0 <= m, n <= 3 * 104
  • 1 <= Node.val <= 105
  • 0 <= skipA <= m
  • 0 <= skipB <= n
  • 如果 listAlistB 没有交点,intersectVal0
  • 如果 listAlistB 有交点,intersectVal == listA[skipA + 1] == listB[skipB + 1]

进阶:你能否设计一个时间复杂度 O(n) 、仅用 O(1) 内存的解决方案?

有三种方法:

1.hash集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}
}

时间复杂度:O(m+n)其中 m 和 n是分别是链表 headA 和 headB 的长度。需要遍历两个链表各一次。

空间复杂度:O(m),其中 m 是链表 headA的长度。需要使用哈希集合存储链表 headA中的全部节点。

2.数学方法:

image-20240113200732376 image-20240113200803805
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA==null || headB==null){
return null;
}
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA!=tempB){
if (tempA==null){
tempA = headB;
}else {
tempA = tempA.next;
}
if (tempB==null){
tempB = headA;
}else {
tempB = tempB.next;
}
}
return tempA;
}
}

时间复杂度:O(m+n),其中 m和 n 是分别是链表 headA和 headB 的长度。两个指针同时遍历两个链表,每个指针遍历两个链表各一次。

空间复杂度:O(1)。

3.尾部对齐:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengthA = 0;
int lengthB = 0;
int gap =0;
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA!=null){
tempA = tempA.next;
lengthA++;
}
while(tempB!=null){
tempB = tempB.next;
lengthB++;
}
if(lengthA>=lengthB){
tempA=headA;
tempB=headB;
gap = lengthA-lengthB;
}else{
tempA=headB;
tempB=headA;
gap = lengthB-lengthA;
}
for(int i=1;i<=gap;i++){
tempA=tempA.next;
}
while(tempA!=null){
if(tempA==tempB){
return tempA;
}else{
tempA=tempA.next;
tempB=tempB.next;
}
}
return null;
}
}

七、环形链表2

力扣题目链接

给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos-1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

不允许修改 链表。

示例 1:

img

1
2
3
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

img

1
2
3
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

img

1
2
3
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。

提示:

  • 链表中节点的数目范围在范围 [0, 104]
  • -105 <= Node.val <= 105
  • pos 的值为 -1 或者链表中的一个有效索引

进阶:你是否可以使用 O(1) 空间解决此题?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
方法一:HashSet的方法
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode pos = head;
Set<ListNode> result = new HashSet<ListNode>();
while(pos!=null){
if(result.contains(pos)){
return pos;
}else{
result.add(pos);
pos = pos.next;
}
}
return null;
}
}

时间复杂度:O(N),其中 N 为链表中节点的数目。恰好需要访问链表中的每一个节点。

空间复杂度:O(N),其中 N 为链表中节点的数目。需要将链表中的每个节点都保存在哈希表当中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 方法二:数学推导,快指针每次前进2个节点,慢指针每次前进1个节点,
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
fast = head;
while(fast!=slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}

八、总结篇

作者

John Doe

发布于

2024-01-11

更新于

2025-02-28

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.