当前位置:  首页>> 技术小册>> 数据结构与算法(下)

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

解法

可以分为3步:

  1. 复制每个节点,并插入到被复制节点的后面。比如1->2->3 clone 1->1->2->2->3->3
  2. 复制随机节点。当遍历到的当前节点存在随机节点时,则其复制节点也应该存在随机节点。比如当前节点cur.random != null,则RandomListNode clone = cur.next;clone.random = cur.random.next;
  3. 分离两个链表。其中奇数链表为原链表,偶数链表为复制的链表

这道题的time complexity为O(n)。

  1. /**
  2. * @author bingo
  3. * @since 2018/11/24
  4. */
  5. /*
  6. public class RandomListNode {
  7. int label;
  8. RandomListNode next = null;
  9. RandomListNode random = null;
  10. RandomListNode(int label) {
  11. this.label = label;
  12. }
  13. }
  14. */
  15. public class Solution {
  16. /**
  17. * 复杂链表的复制
  18. * @param pHead 链表头结点
  19. * @return 复制的链表
  20. */
  21. public RandomListNode Clone(RandomListNode pHead) {
  22. if (pHead == null) {
  23. return null;
  24. }
  25. RandomListNode cur = pHead;
  26. while (cur != null) {
  27. RandomListNode node = new RandomListNode(cur.label);
  28. node.next = cur.next;
  29. cur.next = node;
  30. cur = node.next;
  31. }
  32. cur = pHead;
  33. while (cur != null) {
  34. RandomListNode clone = cur.next;
  35. if (cur.random != null) {
  36. clone.random = cur.random.next;
  37. }
  38. cur = clone.next;
  39. }
  40. cur = pHead;
  41. RandomListNode cloneHead = pHead.next;
  42. while (cur.next != null) {
  43. RandomListNode clone = cur.next;
  44. cur.next = clone.next;
  45. cur = clone;
  46. }
  47. return cloneHead;
  48. }
  49. }

测试用例

  1. 功能测试(结点中的 random 指针指向结点自身;两个结点的 random 形成环状结构;链表中只有一个结点);
  2. 特殊输入测试(指向链表头结点的指针为空指针)。

该分类下的相关小册推荐: