-
struct list_node {
-
struct list_node *next;
-
void *data;
-
};
-
- /*
- 这个函数的名字起得不是特别的好。
- 功能就是返回单链表倒数第n个节点。
- 参数说明:
- struct list_node *head:单链表头指针
- unsigned int pos:倒数的个数
- */
-
struct list_node *get_last_nth_node(struct list_node *head, unsigned int pos)
-
{
-
struct list_node *ret = head;
-
unsigned int i = 0;
-
-
/* 向前步进pos个节点,因为链表个数可能不足,所以需要判断head值是否有效 */
-
while (head && i < pos) {
-
++i;
-
head = head->next;
-
}
-
-
/* head为NULL的话,说明链表个数不足,返回NULL */
-
if (!head) {
-
return NULL;
-
}
-
- /*
- 让ret与head同步向后步进,这样保证了ret与head之间的距离为pos。
- 这样当head到达最后一个节点的时候,ret即为所求的值。
-
*/
-
while (head->next) {
-
ret = ret->next;
-
head = head->next;
-
}
-
-
return ret;
- }