(转)面试大总结之一:Java搞定面试中的链表题目

分类: Algorithm Interview2013-11-16 05:53 11628人阅读 评论(40) 收藏 举报

链表是面试中常出现的一类题目,本文用Java实现了面试中常见的链表相关题目。本文主要参考整合重写了《轻松搞定面试中的链表题目》和 《算法大全(1)单链表》两篇大作。两篇大神的实现分别是C和C#,因为我更喜欢用Java面试,所以用Java重写了所有实现,并附上自己的一些思考注释。算法大全(1)单链表 尚未有一些问题尚未整合进来,很快我会更新本文。接下来还会出关于二叉树的大总结和栈和队列的大总结。因为这些都属于面试中的送分题!必须毫无偏差地拿下。至于像动态规划这些比较“高端”的算法,就只能靠日积月累,而不能像这样临时突击了。

第二篇: 《面试大总结之二:Java搞定面试中的二叉树题目》已经出炉!

[java] view
plain
copy
 
  1. package LinkedListSummary;
  2. import java.util.HashMap;
  3. import java.util.Stack;
  4. /**
  5. * http://blog.csdn.net/luckyxiaoqiang/article/details/7393134 轻松搞定面试中的链表题目
  6. * http://www.cnblogs.com/jax/archive/2009/12/11/1621504.html 算法大全(1)单链表
  7. *
  8. * 目录:
  9. * 1. 求单链表中结点的个数: getListLength
  10. * 2. 将单链表反转: reverseList(遍历),reverseListRec(递归)
  11. * 3. 查找单链表中的倒数第K个结点(k > 0): reGetKthNode
  12. * 4. 查找单链表的中间结点: getMiddleNode
  13. * 5. 从尾到头打印单链表: reversePrintListStack,reversePrintListRec(递归)
  14. * 6. 已知两个单链表pHead1 和pHead2 各自有序,把它们合并成一个链表依然有序: mergeSortedList, mergeSortedListRec
  15. * 7. 判断一个单链表中是否有环: hasCycle
  16. * 8. 判断两个单链表是否相交: isIntersect
  17. * 9. 求两个单链表相交的第一个节点: getFirstCommonNode
  18. * 10. 已知一个单链表中存在环,求进入环中的第一个节点: getFirstNodeInCycle, getFirstNodeInCycleHashMap
  19. * 11. 给出一单链表头指针pHead和一节点指针pToBeDeleted,O(1)时间复杂度删除节点pToBeDeleted: delete
  20. *
  21. */
  22. public class Demo {
  23. public static void main(String[] args) {
  24. Node n1 = new Node(1);
  25. Node n2 = new Node(2);
  26. Node n3 = new Node(3);
  27. Node n4 = new Node(4);
  28. Node n5 = new Node(5);
  29. n1.next = n2;
  30. n2.next = n3;
  31. n3.next = n4;
  32. n4.next = n5;
  33. printList(n1);
  34. //      System.out.println(getListLength(n1));
  35. //      Node head = reverseList(n1);
  36. //      Node head = reverseListRec(n1);
  37. //      printList(head);
  38. Node x = reGetKthNode(n1, 2);
  39. System.out.println(x.val);
  40. reGetKthNodeRec(n1, 2);
  41. //      x = getMiddleNode(head);
  42. //      System.out.println(x.val);
  43. //      System.out.println("reversePrintListStack:");
  44. //      reversePrintListStack(head);
  45. //      System.out.println("reversePrintListRec:");
  46. //      reversePrintListRec(head);
  47. }
  48. //  public static void main(String[] args) {
  49. //      Node n1 = new Node(1);
  50. //      Node n2 = new Node(3);
  51. //      Node n3 = new Node(5);
  52. //      n1.next = n2;
  53. //      n2.next = n3;
  54. //
  55. //      Node m1 = new Node(1);
  56. //      Node m2 = new Node(4);
  57. //      Node m3 = new Node(6);
  58. //      m1.next = m2;
  59. //      m2.next = m3;
  60. //
  61. //
  62. //      Node ret = mergeSortedList(n1, m1);
  63. //      printList(ret);
  64. //  }
  65. private static class Node {
  66. int val;
  67. Node next;
  68. public Node(int val) {
  69. this.val = val;
  70. }
  71. }
  72. public static void printList(Node head) {
  73. while (head != null) {
  74. System.out.print(head.val + " ");
  75. head = head.next;
  76. }
  77. System.out.println();
  78. }
  79. // 求单链表中结点的个数
  80. // 注意检查链表是否为空。时间复杂度为O(n)
  81. public static int getListLength(Node head) {
  82. // 注意头结点为空情况
  83. if (head == null) {
  84. return 0;
  85. }
  86. int len = 0;
  87. Node cur = head;
  88. while (cur != null) {
  89. len++;
  90. cur = cur.next;
  91. }
  92. return len;
  93. }
  94. // 翻转链表(遍历)
  95. // 从头到尾遍历原链表,每遍历一个结点,
  96. // 将其摘下放在新链表的最前端。
  97. // 注意链表为空和只有一个结点的情况。时间复杂度为O(n)
  98. public static Node reverseList(Node head) {
  99. // 如果链表为空或只有一个节点,无需反转,直接返回原链表表头
  100. if (head == null || head.next == null) {
  101. return head;
  102. }
  103. Node reHead = null;         // 反转后新链表指针
  104. Node cur = head;
  105. while (cur != null) {
  106. Node preCur = cur;      // 用preCur保存住对要处理节点的引用
  107. cur = cur.next;             // cur更新到下一个节点
  108. preCur.next = reHead;   // 更新要处理节点的next引用
  109. reHead = preCur;            // reHead指向要处理节点的前一个节点
  110. }
  111. return reHead;
  112. }
  113. // 翻转递归(递归)
  114. // 递归的精髓在于你就默认reverseListRec已经成功帮你解决了子问题了!但别去想如何解决的
  115. // 现在只要处理当前node和子问题之间的关系。最后就能圆满解决整个问题。
  116. /*
  117. head
  118. 1 -> 2 -> 3 -> 4
  119. head
  120. 1--------------
  121. |
  122. 4 -> 3 -> 2                            // Node reHead = reverseListRec(head.next);
  123. reHead      head.next
  124. 4 -> 3 -> 2 -> 1                    // head.next.next = head;
  125. reHead
  126. 4 -> 3 -> 2 -> 1 -> null            // head.next = null;
  127. reHead
  128. */
  129. public static Node reverseListRec(Node head){
  130. if(head == null || head.next == null){
  131. return head;
  132. }
  133. Node reHead = reverseListRec(head.next);
  134. head.next.next = head;      // 把head接在reHead串的最后一个后面
  135. head.next = null;               // 防止循环链表
  136. return reHead;
  137. }
  138. /**
  139. * 查找单链表中的倒数第K个结点(k > 0)
  140. * 最普遍的方法是,先统计单链表中结点的个数,然后再找到第(n-k)个结点。注意链表为空,k为0,k为1,k大于链表中节点个数时的情况
  141. * 。时间复杂度为O(n)。代码略。 这里主要讲一下另一个思路,这种思路在其他题目中也会有应用。
  142. * 主要思路就是使用两个指针,先让前面的指针走到正向第k个结点
  143. * ,这样前后两个指针的距离差是k-1,之后前后两个指针一起向前走,前面的指针走到最后一个结点时,后面指针所指结点就是倒数第k个结点
  144. */
  145. public static Node reGetKthNode(Node head, int k) {
  146. // 这里k的计数是从1开始,若k为0或链表为空返回null
  147. if (k == 0 || head == null) {
  148. return null;
  149. }
  150. Node q = head; // q在p前面  p--q
  151. Node p = head; // p在q后面
  152. // 让q领先p距离k
  153. while (k > 1 && q != null) {
  154. q = q.next;
  155. k--;
  156. }
  157. // 当节点数小于k,返回null
  158. if (k > 1 || q == null) {
  159. return null;
  160. }
  161. // 前后两个指针一起走,直到前面的指针指向最后一个节点
  162. while (q.next != null) {
  163. p = p.next;
  164. q = q.next;
  165. }
  166. // 当前面的指针指向最后一个节点时,后面的指针指向倒数k个节点
  167. return p;
  168. }
  169. /**
  170. * 递归打印出倒数第k位的值
  171. * @param head
  172. * @param dist
  173. */
  174. static int level = 0;
  175. public static void reGetKthNodeRec(Node head, int k) {
  176. if(head == null){
  177. return;
  178. }
  179. if(k == 1){
  180. return;
  181. }
  182. reGetKthNodeRec(head.next, k);
  183. level++;
  184. if(level == k) {
  185. System.out.println(head.val);
  186. }
  187. }
  188. // 查找单链表的中间结点
  189. /**
  190. * 此题可应用于上一题类似的思想。也是设置两个指针,只不过这里是,两个指针同时向前走,前面的指针每次走两步,后面的指针每次走一步,
  191. * 前面的指针走到最后一个结点时,后面的指针所指结点就是中间结点,即第(n/2+1)个结点。注意链表为空,链表结点个数为1和2的情况。时间复杂度O(n
  192. */
  193. public static Node getMiddleNode(Node head) {
  194. if (head == null || head.next == null) {
  195. return head;
  196. }
  197. Node q = head;      // p---q
  198. Node p = head;
  199. // 前面指针每次走两步,直到指向最后一个结点,后面指针每次走一步
  200. while (q.next != null) {
  201. q = q.next;
  202. p = p.next;
  203. if (q.next != null) {
  204. q = q.next;
  205. }
  206. }
  207. return p;
  208. }
  209. /**
  210. * 从尾到头打印单链表
  211. * 对于这种颠倒顺序的问题,我们应该就会想到栈,后进先出。所以,这一题要么自己使用栈,要么让系统使用栈,也就是递归。注意链表为空的情况
  212. * 。时间复杂度为O(n)
  213. */
  214. public static void reversePrintListStack(Node head) {
  215. Stack<Node> s = new Stack<Node>();
  216. Node cur = head;
  217. while (cur != null) {
  218. s.push(cur);
  219. cur = cur.next;
  220. }
  221. while (!s.empty()) {
  222. cur = s.pop();
  223. System.out.print(cur.val + " ");
  224. }
  225. System.out.println();
  226. }
  227. /**
  228. * 从尾到头打印链表,使用递归(优雅!)
  229. */
  230. public static void reversePrintListRec(Node head) {
  231. if (head == null) {
  232. return;
  233. } else {
  234. reversePrintListRec(head.next);
  235. System.out.print(head.val + " ");
  236. }
  237. }
  238. /**
  239. * 已知两个单链表pHead1 和pHead2 各自有序,把它们合并成一个链表依然有序
  240. * 这个类似归并排序。尤其注意两个链表都为空,和其中一个为空时的情况。只需要O(1)的空间。时间复杂度为O(max(len1, len2))
  241. */
  242. public static Node mergeSortedList(Node head1, Node head2) {
  243. // 其中一个链表为空的情况,直接返回另一个链表头,O(1)
  244. if (head1 == null) {
  245. return head2;
  246. }
  247. if (head2 == null) {
  248. return head1;
  249. }
  250. Node mergeHead = null;
  251. // 先确定下来mergeHead是在哪里
  252. if (head1.val < head2.val) {
  253. mergeHead = head1;
  254. head1 = head1.next;         // 跳过已经合并了的元素
  255. mergeHead.next = null;  // 断开mergeHead和后面的联系
  256. } else {
  257. mergeHead = head2;
  258. head2 = head2.next;
  259. mergeHead.next = null;
  260. }
  261. Node mergeCur = mergeHead;
  262. while (head1 != null && head2 != null) {
  263. if (head1.val < head2.val) {
  264. mergeCur.next = head1;       // 把找到较小的元素合并到merge中
  265. head1 = head1.next;              // 跳过已经合并了的元素
  266. mergeCur = mergeCur.next;    // 找到下一个准备合并的元素
  267. mergeCur.next = null;            // 断开mergeCur和后面的联系
  268. } else {
  269. mergeCur.next = head2;
  270. head2 = head2.next;
  271. mergeCur = mergeCur.next;
  272. mergeCur.next = null;
  273. }
  274. }
  275. // 合并剩余的元素
  276. if (head1 != null) {
  277. mergeCur.next = head1;
  278. } else if (head2 != null) {
  279. mergeCur.next = head2;
  280. }
  281. return mergeHead;
  282. }
  283. /**
  284. * 递归合并两链表(优雅!)
  285. */
  286. public static Node mergeSortedListRec(Node head1, Node head2) {
  287. if (head1 == null) {
  288. return head2;
  289. }
  290. if (head2 == null) {
  291. return head1;
  292. }
  293. Node mergeHead = null;
  294. if (head1.val < head2.val) {
  295. mergeHead = head1;
  296. // 连接已解决的子问题
  297. mergeHead.next = mergeSortedListRec(head1.next, head2);
  298. } else {
  299. mergeHead = head2;
  300. mergeHead.next = mergeSortedListRec(head1, head2.next);
  301. }
  302. return mergeHead;
  303. }
  304. /**
  305. * 判断一个单链表中是否有环
  306. * 这里也是用到两个指针。如果一个链表中有环,也就是说用一个指针去遍历,是永远走不到头的。因此,我们可以用两个指针去遍历,一个指针一次走两步
  307. * ,一个指针一次走一步,如果有环,两个指针肯定会在环中相遇。时间复杂度为O(n)
  308. */
  309. public static boolean hasCycle(Node head) {
  310. Node fast = head; // 快指针每次前进两步
  311. Node slow = head; // 慢指针每次前进一步
  312. while (fast != null && fast.next != null) {
  313. fast = fast.next.next;
  314. slow = slow.next;
  315. if (fast == slow) { // 相遇,存在环
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. // 判断两个单链表是否相交
  322. /**
  323. * 如果两个链表相交于某一节点,那么在这个相交节点之后的所有节点都是两个链表所共有的。 也就是说,如果两个链表相交,那么最后一个节点肯定是共有的。
  324. * 先遍历第一个链表,记住最后一个节点,然后遍历第二个链表, 到最后一个节点时和第一个链表的最后一个节点做比较,如果相同,则相交,
  325. * 否则不相交。时间复杂度为O(len1+len2),因为只需要一个额外指针保存最后一个节点地址, 空间复杂度为O(1)
  326. */
  327. public static boolean isIntersect(Node head1, Node head2) {
  328. if (head1 == null || head2 == null) {
  329. return false;
  330. }
  331. Node tail1 = head1;
  332. // 找到链表1的最后一个节点
  333. while (tail1.next != null) {
  334. tail1 = tail1.next;
  335. }
  336. Node tail2 = head2;
  337. // 找到链表2的最后一个节点
  338. while (tail2.next != null) {
  339. tail2 = tail2.next;
  340. }
  341. return tail1 == tail2;
  342. }
  343. /**
  344. * 求两个单链表相交的第一个节点 对第一个链表遍历,计算长度len1,同时保存最后一个节点的地址。
  345. * 对第二个链表遍历,计算长度len2,同时检查最后一个节点是否和第一个链表的最后一个节点相同,若不相同,不相交,结束。
  346. * 两个链表均从头节点开始,假设len1大于len2
  347. * ,那么将第一个链表先遍历len1-len2个节点,此时两个链表当前节点到第一个相交节点的距离就相等了,然后一起向后遍历,直到两个节点的地址相同。
  348. * 时间复杂度,O(len1+len2)
  349. *
  350. *              ----    len2
  351. *                   |__________
  352. *                   |
  353. *       ---------   len1
  354. *       |---|<- len1-len2
  355. */
  356. public static Node getFirstCommonNode(Node head1, Node head2) {
  357. if (head1 == null || head2 == null) {
  358. return null;
  359. }
  360. int len1 = 1;
  361. Node tail1 = head1;
  362. while (tail1.next != null) {
  363. tail1 = tail1.next;
  364. len1++;
  365. }
  366. int len2 = 1;
  367. Node tail2 = head2;
  368. while (tail2.next != null) {
  369. tail2 = tail2.next;
  370. len2++;
  371. }
  372. // 不相交直接返回NULL
  373. if (tail1 != tail2) {
  374. return null;
  375. }
  376. Node n1 = head1;
  377. Node n2 = head2;
  378. // 略过较长链表多余的部分
  379. if (len1 > len2) {
  380. int k = len1 - len2;
  381. while (k != 0) {
  382. n1 = n1.next;
  383. k--;
  384. }
  385. } else {
  386. int k = len2 - len1;
  387. while (k != 0) {
  388. n2 = n2.next;
  389. k--;
  390. }
  391. }
  392. // 一起向后遍历,直到找到交点
  393. while (n1 != n2) {
  394. n1 = n1.next;
  395. n2 = n2.next;
  396. }
  397. return n1;
  398. }
  399. /**
  400. * 求进入环中的第一个节点 用快慢指针做(本题用了Crack the Coding Interview的解法,因为更简洁易懂!)
  401. */
  402. public static Node getFirstNodeInCycle(Node head) {
  403. Node slow = head;
  404. Node fast = head;
  405. // 1) 找到快慢指针相遇点
  406. while (fast != null && fast.next != null) {
  407. slow = slow.next;
  408. fast = fast.next.next;
  409. if (slow == fast) { // Collision
  410. break;
  411. }
  412. }
  413. // 错误检查,这是没有环的情况
  414. if (fast == null || fast.next == null) {
  415. return null;
  416. }
  417. // 2)现在,相遇点离环的开始处的距离等于链表头到环开始处的距离,
  418. // 这样,我们把慢指针放在链表头,快指针保持在相遇点,然后
  419. // 同速度前进,再次相遇点就是环的开始处!
  420. slow = head;
  421. while (slow != fast) {
  422. slow = slow.next;
  423. fast = fast.next;
  424. }
  425. // 再次相遇点就是环的开始处
  426. return fast;
  427. }
  428. /**
  429. * 求进入环中的第一个节点 用HashMap做 一个无环的链表,它每个结点的地址都是不一样的。
  430. * 但如果有环,指针沿着链表移动,那这个指针最终会指向一个已经出现过的地址 以地址为哈希表的键值,每出现一个地址,就将该键值对应的实值置为true。
  431. * 那么当某个键值对应的实值已经为true时,说明这个地址之前已经出现过了, 直接返回它就OK了
  432. */
  433. public static Node getFirstNodeInCycleHashMap(Node head) {
  434. HashMap<Node, Boolean> map = new HashMap<Node, Boolean>();
  435. while (head != null) {
  436. if (map.get(head) == true) {
  437. return head; // 这个地址之前已经出现过了,就是环的开始处
  438. } else {
  439. map.put(head, true);
  440. head = head.next;
  441. }
  442. }
  443. return head;
  444. }
  445. /**
  446. * 给出一单链表头指针head和一节点指针toBeDeleted,O(1)时间复杂度删除节点tBeDeleted
  447. * 对于删除节点,我们普通的思路就是让该节点的前一个节点指向该节点的下一个节点
  448. * ,这种情况需要遍历找到该节点的前一个节点,时间复杂度为O(n)。对于链表,
  449. * 链表中的每个节点结构都是一样的,所以我们可以把该节点的下一个节点的数据复制到该节点
  450. * ,然后删除下一个节点即可。要注意最后一个节点的情况,这个时候只能用常见的方法来操作,先找到前一个节点,但总体的平均时间复杂度还是O(1)
  451. */
  452. public void delete(Node head, Node toDelete){
  453. if(toDelete == null){
  454. return;
  455. }
  456. if(toDelete.next != null){          // 要删除的是一个中间节点
  457. toDelete.val = toDelete.next.val;       // 将下一个节点的数据复制到本节点!
  458. toDelete.next = toDelete.next.next;
  459. }
  460. else{       // 要删除的是最后一个节点!
  461. if(head == toDelete){       // 链表中只有一个节点的情况
  462. head = null;
  463. }else{
  464. Node node = head;
  465. while(node.next != toDelete){   // 找到倒数第二个节点
  466. node = node.next;
  467. }
  468. node.next = null;
  469. }
  470. }
  471. }
  472. }
上一篇:Delphi中使用python脚本读取Excel数据


下一篇:使用shell程序备份crontab中的.sh脚本文件