一道超难的算法题-复制链表

Rui在参加面试后,给我分享了一道算法题。他在留言中说made me wanna kill myself when I knew the answer.

题目如下:

Given a Linked List of node structure asstruct Node { type element; Node *next; Node *arb;};You are asked to create an exact copy this linked list. Pointer arb points to an arbitrary node in the linked list.

先说说我的算法吧。我选择了一个超笨的方法完成:创建一个新的linked list存储原始链表每个节点的顺序号,然后复制链表的时候,通过顺序号,找到arb指针所指向的节点。算法很笨,无论是空间效率还是时间效率,都很差。不过好歹是完成了。

不过,在我看完答案之后,我也wanna kill myslef。太神奇了。

算法首先在每两个节点之间插入一个新的节点。然后循环每组节点:

  1. p->next->arb = p->arb->next;
  2. p = p->next->next;

我顺手写了段实现代码,没编译,没调试,没测试。

  1. typedef struct {
  2.     int data; // assuming data is an integer
  3.     Node *next;
  4.     Node *arb;
  5. }Node;
  6.  
  7. void copy_linked_list(Node * src, Node ** dst) {
  8.     Node *p;
  9.     Node *q = NULL;
  10.  
  11.     for (p = src; p; p=p->next->next) {
  12.         // Initialize the new node
  13.         Note *nn = (Node *)malloc(sizeof(Node));
  14.         nn->data = p->data;
  15.         nn->arb = NULL;
  16.  
  17.         // Add the node to the right of the src node
  18.         nn->next = p->next;
  19.         p->next = nn;
  20.     }
  21.  
  22.     // Create arb pointer
  23.     for(p = src; p; p = p->next->next)
  24.         p->next->arb = p->arb->next;
  25.  
  26.     // Detach copy node and create destination linked list
  27.     for (p = src, q = *dst; p; p = p->next-next, q = q->next) {
  28.         r = p->next;
  29.         p->next = p->next-next;
  30.         if (q->next)
  31.             q->next = q->next->next;
  32.         else
  33.             q->next = NULL;
  34.         if (q)
  35.             q = r;
  36.         else
  37.             q->next = r;
  38.     }
  39. }

其实Rui早在3月份就给我发了这道题目,我也早在几个月前,看到了正确答案。一直想把这道题作为面试题,可觉得太难了,不想难为candidate了。

Posted by Wei@11:14 July 16th, 2008 CDT in Computer Science | Permalink | Trackback.

Leave a comment

Please be polite and on topic. Your e-mail will never be published.