Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1674216
  • 博文数量: 782
  • 博客积分: 2455
  • 博客等级: 大尉
  • 技术积分: 4140
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-06 21:37
个人简介

Linux ,c/c++, web,前端,php,js

文章分类

全部博文(782)

文章存档

2015年(8)

2014年(28)

2013年(110)

2012年(307)

2011年(329)

分类:

2011-08-13 09:49:29

本文的copyleft归gfree.wind@gmail.com所有,使用GPL发布,可以自由拷贝,转载。但转载请保持文档的完整性,注明原作者及原链接,严禁用于任何商业用途。
作者:gfree.wind@gmail.com
博客:linuxfocus.blog.chinaunix.net
 

这是一个比较常见的面试算法题——不过我还真没遇到过这道题——呵呵,这是因为我也好久没有换工作了。目前既然有这个打算,牛刀小试一下吧。

  1. struct list_node {
  2.     struct list_node *next;
  3.     void *data;
  4. };

  5. /*
  6. 这个函数的名字起得不是特别的好。
  7. 功能就是返回单链表倒数第n个节点。
  8. 参数说明:
  9. struct list_node *head:单链表头指针
  10. unsigned int pos:倒数的个数
  11. */
  12. struct list_node *get_last_nth_node(struct list_node *head, unsigned int pos)
  13. {
  14.     struct list_node *ret = head;
  15.     unsigned int i = 0;

  16.     /* 向前步进pos个节点,因为链表个数可能不足,所以需要判断head值是否有效 */
  17.     while (head && i < pos) {
  18.         ++i;
  19.         head = head->next;
  20.     }

  21.     /* head为NULL的话,说明链表个数不足,返回NULL */
  22.     if (!head) {
  23.         return NULL;
  24.     }

  25.     /* 
  26.     让ret与head同步向后步进,这样保证了ret与head之间的距离为pos。
  27.     这样当head到达最后一个节点的时候,ret即为所求的值。
  28.     */
  29.     while (head->next) {
  30.         ret = ret->next;
  31.         head = head->next;
  32.     }

  33.     return ret;
  34. }

阅读(226) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~