Press "Enter" to skip to content

Posts published in “List”

花花酱 LeetCode 203. Remove Linked List Elements

题目大意:移除单向链表中所有值等于val的节点。

Problem:

https://leetcode.com/problems/remove-linked-list-elements/description/

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

Idea:

Use a dummy head

Solution:

Time complexity: O(n)

Space complexity: O(1)

C++

 

花花酱 LeetCode 234. Palindrome Linked List

题目大意:检查一个单向链表是不是回文。

Problem:

https://leetcode.com/problems/palindrome-linked-list/description/

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Idea:

  1. use fast / slow pointers to find the middle node and see whether the list has odd/even number of elements.
  2. Reverse the right half the list, and compare with the left half

E.g.
1->2->3->4->3->2->1->null
fast = null
slow = 4
slow->next = 3
reverse(slow->next)
null<-3<-2<-1 compare with 1->2->3->…

Solution: 1

Time complexity: O(n)

Space complexity: O(1)

C++

 

 

 

花花酱 LeetCode 206. Reverse Linked List

题目大意:反转一个单向链表

Problem:

https://leetcode.com/problems/reverse-linked-list/description/

Reverse a singly linked list.

Solution 1:

Tracking prev / curr / next node

Time complexity: O(n)

Space complexity: O(1)

C++

Java

Python 3

 

花花酱 LeetCode 725. Split Linked List in Parts

Problem:

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:

Example 2:

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].



Idea:
List + Simulation
Solution:
C++

Java

Python

 

花花酱 LeetCode 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.

Solution 1: Iterative O(n)

 

Solution 2: Recursive O(n)