# Posts published in “List”

Problem:

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:

Solution:

Time complexity: O(n)

Space complexity: O(1)

C++

Problem:

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

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++

Problem:

Solution 1:

Tracking prev / curr / next node

Time complexity: O(n)

Space complexity: O(1)

C++

Java

Python 3

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 [ , , , , 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

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)