递归算法中的链表操作 - Go语言中文社区

递归算法中的链表操作


今天,打算将问题深入一下,即添加相应的操作在递归的过程中。

(免责声明:下面的解法纯属娱乐 ,另外,示例代码未经编译和调试,许多想法未经实践验证。)

查找链表当中倒数第N个节点。

解法一

逐层递归,遍历到最后一个节点,并从返回的节点一次向后递归,遍历N次,找到倒数第N个节点。

  1. private LNode targetNode = null
  2. private LNode FindLastNthNode(LNode head, int index) 
  3.     if (head.Next == null
  4.     { 
  5.         return head; 
  6.     } 
  7.  
  8.     FindLastNthNode(head.Next, index); 
  9.  
  10.     LNode tmpNode = head; 
  11.  
  12.     while ((head.Next != null) && (index > 0)) 
  13.     { 
  14.         head = head.Next; 
  15.         index--; 
  16.     } 
  17.  
  18.     if (head.Next == null && index == 0) 
  19.     { 
  20.         targetNode = tmpNode; 
  21.         return targetNode; 
  22.     } 
  23.  
  24.     return targetNode; 
  25.  

分析

1. 额外的全局性的辅助变量。

2. 时间复杂度为O(index * n),n为链表的长度。

3. 性能开销较大。

解法二(解法一的变形)

每当遍历到当前节点,即再循环向后遍历n个,如果节点遍历到最后,并且index自减等于0,说明当前节点即为要找的倒数第n个。也就是说解法一是从后向前找,而解法二是从前向后找。

  1. private LNode targetNode2 = null
  2.  
  3. private LNode FindLastNthNode2(LNode head, int index) 
  4.     if (head.Next == null
  5.         return head; 
  6.  
  7.     LNode tmpNode = head; 
  8.  
  9.     while (head != null && index >= 0) 
  10.     { 
  11.         head = head.Next; 
  12.         index--; 
  13.     } 
  14.  
  15.     if (head == null && index == 0) 
  16.     { 
  17.         targetNode2 = tmpNode; 
  18.         return targetNode2; 
  19.     } 
  20.  
  21.     return targetNode2; 

分析:与解法一一样。

解法三

  1. private int counter = 0; 
  2. private LNode targetNode2; 
  3.  
  4. private LNode FindLastNthNode2(LNode head, int index) 
  5.     if (head.Next == null
  6.     { 
  7.         counter = index; 
  8.         return head; 
  9.     } 
  10.  
  11.     FindLastNthNode2(head.Next, index); 
  12.  
  13.     counter--; 
  14.  
  15.     if (counter == 0) 
  16.     { 
  17.         targetNode2 = head; 
  18.         return targetNode2; 
  19.     } 
  20.  
  21.     return targetNode2; 
定义一个全局变量,用来计数,当递归从最后一个节点返回时,计数器减减,当等于0时,这个节点即是要找的倒数第N个节点分析
1. 两个辅助变量。
2. 时间复杂度为O(n)。
3. 多余的index,累赘的counter。

版权声明:本文来源51CTO,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:http://developer.51cto.com/art/201208/351303.htm
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 04:10:50
  • 阅读 ( 1166 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢