现在的位置: 首页 > 综合 > 正文

一道笔试题——寻找单链表的倒数第n个节点

2013年07月26日 ⁄ 综合 ⁄ 共 1475字 ⁄ 字号 评论关闭

闲逛的时候,看到一据说是腾讯的笔试题:

找出单链表的倒数第n个节点,自己写了一下:

Code:
  1. typedef struct node  
  2. {  
  3.     int data;  
  4.     struct node *next;  
  5. } link_node;  
  6.   
  7.  
  8. //第一种方法
  9. // 找出倒数第n个节点,返回其指针   
  10. link_node *find_n (link_node *head, int n)  
  11. {  
  12.     link_node *p = head;  
  13.     int num_node = 0;  
  14.     if (p == NULL) //链表为空  
  15.     {  
  16.         printf ("the link list is empty./n");  
  17.         return NULL;  
  18.     }  
  19.       
  20.     while (p->next != NULL) //统计节点个数 复杂度:O(list_length)   
  21.     {  
  22.         num_node++;  
  23.         p = p->next;  
  24.     }  
  25.     if (num_node < n)  
  26.     {  
  27.         printf ("the length of the link list is %d/n", num_node);  
  28.         return NULL;  
  29.     }  
  30.       
  31.     //总共有num_node个,则倒数第n个即正数第num_node-n+1个  
  32.     p = head;  
  33.     int i = 1;  
  34.     while (i < num_node - n + 1) //时间复杂度:O(list_length-n)   
  35.     {  
  36.         p = p->next;  
  37.         i++;  
  38.     }  
  39.       
  40.     return p;  
  41. }  
  42.   
  43. // 第二种方法
  44. /** 设置两个指针p1,p2,让p1与p2间隔n-1个节点,即让p2指向 
  45.     正数第n个节点,然后顺次后移, 
  46.     当p2到达末尾时,p1指向倒数第n个节点 
  47. */  
  48. link_node *find_n (link_node *head, int n)  
  49. {  
  50.     link_node *p1 = head, *p2 = head;  
  51.     int i = 1;  
  52.     while ((i < n) && (p2 != NULL))  
  53.     {  
  54.         p2 = p2->next;  
  55.         i++;  
  56.     }  
  57.     if (i != n)   //说明链表节点个数不足n  
  58.     {  
  59.         printf ("the node number is less than %d/n", n);  
  60.         return NULL;  
  61.     }  
  62.     while (p2->next != NULL)  
  63.     {  
  64.         p1 = p1->next;  
  65.         p2 = p2->next;  
  66.     }  
  67.       
  68.     return p1;  
  69. }  
  70.       
  71.    
  72.        
  73.       
  74.       

可能有的同学认为第一种方法不值一提,但分析一下时间复杂度,会发现两种方法的时间复杂度都是O(list_length) + O(list_length-n)。

如哪位兄台有更好的办法,不妨指点一下。

抱歉!评论已关闭.