LeetCode 链表
\2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
解答:
1 | # Definition for singly-linked list. |
\19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
1 | Given linked list: 1->2->3->4->5, and n = 2. |
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
1 | # Definition for singly-linked list. |
\21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
1 | Input: 1->2->4, 1->3->4 |
1 | # iteratively |
\23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
1 | Input: |
思路参考上题,采用二分法,两两组合。
1 | # Definition for singly-linked list. |
方法二:pythonic的方法,使用heapq–堆队列算法
\24. Swap Nodes in Pairs**
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
1 | Given 1->2->3->4, you should return the list as 2->1->4->3. |
1 | # Definition for singly-linked list. |
\25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
Reverse思路见下题,主要就是分成k组,分别使用reverse
1 | # Definition for singly-linked list. |
\206. Reverse Linked List
Reverse a singly linked list.
Example:
1 | Input: 1->2->3->4->5->NULL |
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
递归方法:
1 | # Definition for singly-linked list. |
1 | #迭代方法 |
\92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
1 | Input: 1->2->3->4->5->NULL, m = 2, n = 4 |
1 | # Definition for singly-linked list. |
\61. Rotate List
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
1 | Input: 1->2->3->4->5->NULL, k = 2 |
Example 2:
1 | Input: 0->1->2->NULL, k = 4 |
思路一:连成环
1 | # Definition for singly-linked list. |
\83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
1 | Input: 1->1->2 |
Example 2:
1 | Input: 1->1->2->3->3 |
#Microsoft 一面
1 | # Definition for singly-linked list. |
\82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
1 | Input: 1->2->3->3->4->4->5 |
Example 2:
1 | Input: 1->1->1->2->3 |
#Microsoft 一面
1 | # Definition for singly-linked list. |
\86. Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
1 | Input: head = 1->4->3->2->5->2, x = 3 |
思路:本题大意,给定一个值x,在保持链表元素相对位置不变的情况下,小于x的元素在大于x的元素之前
创建两个列表,遍历原始链表,第一个链表存储小的元素,第二个存储大的元素,最后拼接返回
1 | # Definition for singly-linked list. |
\109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
1 | Given the sorted linked list: [-10,-3,0,5,9], |
思路:二叉树的递归定义为:左子树的值均小于根节点的值,右子树的值均大于根节点的值。(若左右子树不为空)。
平衡树的递归定义为:左右子树的高度差小于等于1.
因为给的数据是排序好的,又是一棵平衡树,所以用二分依次递归。与array的区别就是,不能用索引,只能用指针来将列表不断分割,方法:快慢指针,速度两倍。
1 | # Definition for singly-linked list. |
\138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Example 1:
1 | Input: |
Note:
- You must return the copy of the given head as a reference to the cloned list.
题目大意:
给你一个特殊的链表,你要复制它,这个链表的特殊部分在于多了random指针,random指针可以指向任意节点,若暴力方法,每当指向链表某一个节点你都要遍历找到那个结点,然后复制。时间肯定不满足要求,
方法一:使用HashMap将每个结点的值复制存储起来。然后第二轮对链表迭代,更新HashMap中的next和random指针。
1 | """ |
方法二:遍历指针是,在每一个结点后面复制一个结点,然后第二次迭代将两个链表分开
1 | """ |
\141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Example 1:
1 | Input: head = [3,2,0,-4], pos = 1 |
Example 2:
1 | Input: head = [1,2], pos = 0 |
Example 3:
1 | Input: head = [1], pos = -1 |
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
思路:快慢指针,如果有环总会相遇
1 | # Definition for singly-linked list. |
\142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
1 | Input: head = [3,2,0,-4], pos = 1 |
Example 2:
1 | Input: head = [1,2], pos = 0 |
Example 3:
1 | Input: head = [1], pos = -1 |
Follow-up:
Can you solve it without using extra space?
思路如下:
1 | # Definition for singly-linked list. |
\143. Reorder List
Given a singly linked list L: L0→L1→…→L**n-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→L**n-2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example 1:
1 | Given 1->2->3->4, reorder it to 1->4->2->3. |
Example 2:
1 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. |
思路:快慢指针分为两个链表,第二个链表反转,然后两个链表合并。
1 | # Definition for singly-linked list. |
\147. Insertion Sort List
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
Example 1:
1 | Input: 4->2->1->3 |
Example 2:
1 | Input: -1->5->3->4->0 |
思路:构造一个新链表,依次插入
1 | # Definition for singly-linked list. |
\148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
1 | Input: 4->2->1->3 |
Example 2:
1 | Input: -1->5->3->4->0 |
思路:nlogn -> merge sort
1 | # Definition for singly-linked list. |
\160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Example 1:
1 | Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 |
Example 2:
1 | Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 |
Example 3:
1 | Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 |
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
1 | #method 1: 需要距离 |
\203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val\.
Example:
1 | Input: 1->2->6->3->4->5->6, val = 6 |
类似\82. Remove Duplicates from Sorted List II
1 | class Solution: |
\234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
1 | Input: 1->2 |
Example 2:
1 | Input: 1->2->2->1 |
Follow up:
Could you do it in O(n) time and O(1) space?
水题,注意fast指针由于链表结点的奇偶情况,结束的不同情况。
1 | class Solution: |
\237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
Example 1:
1 | Input: head = [4,5,1,9], node = 5 |
Example 2:
1 | Input: head = [4,5,1,9], node = 1 |
Note:
- The linked list will have at least two elements.
- All of the nodes’ values will be unique.
- The given node will not be the tail and it will always be a valid node of the linked list.
- Do not return anything from your function.
\237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
Example 1:
1 | Input: head = [4,5,1,9], node = 5 |
Example 2:
1 | Input: head = [4,5,1,9], node = 1 |
Note:
The linked list will have at least two elements.
All of the nodes’ values will be unique.
The given node will not be the tail and it will always be a valid node of the linked list.
Do not return anything from your function.
奇葩题
1
2
3
4
5
6
7
8class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
\445. Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
1 | Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) |
1 | class Solution: |
\725. Split Linked List in Parts
Given a (singly) linked list with head node root
, write a function to split the linked list into k
consecutive linked list “parts”.
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode’s representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
Example 1:
1 | Input: |
Example 2:
1 | Input: |
Note:
The length of root
will be in the range [0, 1000]
.
Each value of a node in the input will be an integer in the range [0, 999]
.
k
will be an integer in the range [1, 50]
.
思路:参考大佬的题解
This question can be split into two parts
- Count the length of the linked list
- Determine the length of nodes in each chunk
- Splitting the linked list up
At the end of step 2, res
will look something like this, for a list of length 10 and k of 3: [4, 4, 3]
.
Step 3 iterates through res
using the values in res
and replaces the value at each index with each chunk’s head node. We have to keep a reference to prev
in order to slice up the chunks nicely by setting prev.next = None
.
- Yangshun
1 | class Solution: |
\430. Flatten a Multilevel Doubly Linked List
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example 1:
1 | Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] |
Example 2:
1 | Input: head = [1,2,null,3] |
Example 3:
1 | Input: head = [] |
How multilevel linked list is represented in test case:
We use the multilevel linked list from Example 1 above:
1 | 1---2---3---4---5---6--NULL |
The serialization of each level is as follows:
1 | [1,2,3,4,5,6,null] |
To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
1 | [1,2,3,4,5,6,null] |
Merging the serialization of each level and removing trailing nulls we obtain:
1 | [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] |
Constraints:
Number of Nodes will not exceed 1000.
1 <= Node.val <= 10^5
思路:使用栈
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"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return head
stk = [head]
prev = Node(0)
while stk:
root = stk.pop()
root.prev = prev
prev.next = root
prev = root
if root.next:
stk.append(root.next)
if root.child:
stk.append(root.child)
root.child = None
head.prev = None
return head
\817. Linked List Components
We are given head
, the head node of a linked list containing unique integer values.
We are also given the list G
, a subset of the values in the linked list.
Return the number of connected components in G
, where two values are connected if they appear consecutively in the linked list.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
Note:
If
N
is the length of the linked list given byhead
,1 <= N <= 10000
.The value of each node in the linked list will be in the range
[0, N - 1]
.1 <= G.length <= 10000
.G
is a subset of all values in the linked list.题目大意:给定一个链表,链表中的元素均不重复,给定一个列表G,是链表元素值的子集。返回G中的连续部分。
算法:遍历每一个链表中的每一个元素,若这个元素在G中则遍历下一个,作为一个部分。直至遍历结束。
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
28class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
dic = {num: 1 for num in G}
comp = []
while head:
cur = []
while head and head.val in dic:
cur.append(head.val)
head = head.next
if cur:
comp.append(cur)
if head:
head = head.next
return len(comp)
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
set_G = set(G)
res = cnt = 0
while head:
if head.val in set_G:
cnt += 1
else:
res += 1 if cnt else 0
cnt = 0
head = head.next
return res+1 if cnt else res\1019. Next Greater Node In Linked List
We are given a linked list with head
as the first node. Let’s number the nodes in the list: node_1, node_2, node_3, ...
etc.
Each node may have a next larger value: for node_i
, next_larger(node_i)
is the node_j.val
such that j > i
, node_j.val > node_i.val
, and j
is the smallest possible choice. If such a j
does not exist, the next larger value is 0
.
Return an array of integers answer
, where answer[i] = next_larger(node_{i+1})
.
Note that in the example inputs (not outputs) below, arrays such as [2,1,5]
represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.
Example 1:
1 | Input: [2,1,5] |
Example 2:
1 | Input: [2,7,4,3,5] |
Example 3:
1 | Input: [1,7,5,1,9,2,5,1] |
Note:
1 <= node.val <= 10^9
for each node in the linked list.- The given list has length in the range
[0, 10000]
思路:本题要找每个元素的后续结点中第一个大于该节点的值,并输出。使用stack
1 | class Solution: |
\1171. Remove Zero Sum Consecutive Nodes from Linked List
Given the head
of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0
until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of ListNode
objects.)
Example 1:
1 | Input: head = [1,2,-3,3,1] |
Example 2:
1 | Input: head = [1,2,3,-3,4] |
Example 3:
1 | Input: head = [1,2,3,-3,-2] |
Constraints:
- The given linked list will contain between
1
and1000
nodes. - Each node in the linked list has
-1000 <= node.val <= 1000
.
思路:prefix,当prefix的值等于之前元素的prefix值时,说明这两个元素之间的元素之和为0。
1 | class ListNode: |
- Blog Link: http://songjingrui.github.io/2019/12/17/LeetCode-%E9%93%BE%E8%A1%A8/
- Copyright Declaration: The author owns the copyright, please indicate the source reproduced.