Cracking the coding interview--Q2

Chapter 2 | Linked Lists

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

hash,否則只能o(n平方)

2.2 Implement an algorithm to find the nth to last element of a singly linked list.

先遍歷鏈表得到長度s,再從頭向尾移動s-n。原解是棧,也ok,前提是讓用額外的空間

2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. EXAMPLE Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e

沒有頭節點的時候就是把d的數據移動到了c上,真是trick...但尾節點要注意用trick來保證不被遍歷到

2.4 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. EXAMPLE Input: (3 –> 1 –> 5) + (5 –> 9 –> 2) Output: 8 –> 0 –> 8

實現加法計算。。進一。

2.5 Given a circular linked list, implement an algorithm which returns node at the beginning of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE input: A –> B –> C –> D –> E –> C (the same C as earlier) output: C

hash所有節點的指針值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章