[CC150] Chapter 2 Linked Lists

2.1 Write code to remove duplicates from an unsorted linked list. How would you solve this problem if a temporary buffer is not allowed?

Related problems: Remove Duplicate from Sorted List and Remove Duplicate from Sorted List II.

Following code defines a class LinkedList, which provides several methods:
CreateList: create a linked list from a given vector of integers
PrintList: print out the linked list for debugging
removeDuplicates: remove duplicates using a hash set
removeDupNoBuffer: remove duplicates without buffer (O(n^2) in time)
2.2 Implement an algorithm to find the kth to last element of a singly linked list.

This problem is in leetcode as Remove Nth Node From End of List.

2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

The only way is to copy the next node to the current node, and then delete the next node. If the node to be deleted is the last one, you cannot delete it. Probably we could change the value to a specific value (mark the node as unused).
2.4 Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.

This problem is in leetcode as Partition List.

2.5 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
FOLLOWUP:
Suppose the digits are stored in forward order. Repeat the above problem.

This problem is in leetcode as Add Two Numbers. The follow up is essentially the same, although the implementation details change.

2.6 Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop.

This problem is in leetcode as Linked List Cycle II. Related problem: Linked List Cycle.

2.7 Implement a function to check if a linked list is a palindrome.

Using stack is straightforward. Other solutions include recursion and reverse the linked list.
Note that if the linked list contains odd numbers, the middle one should be ignored.

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design