结点是从0开始计算的
if (p == NULL || pos == 0)
{
return head;
}
p == NULL 代表链表为空,pos == 0 时表示我们要找的是链表中第一个元素的位置,满足这两个条件时都返回头指针head。
for (int i = 0; p && i < pos; i++)
{
p = p->next;
}
return p;
跳转之后,执行循环操作,判断条件首先需要检测指针p是否为空,而条件 i<pos 则是在确保执行次数,即确定循环到指定位置。循环内部,p = p->next 的执行结果是让p指向p所指向的结点里的 next 指针所指向的位置。
那么,之前已经判断过 p 是否为空,为何在循环条件里边还要加?
我们可以这样解释,如果我们指定的位置超出链表的范围,此时在执行的 p 指向最后一个结点的时候,next 即 p 已经为空,所以此处加上这个条件就可以终止循环。如果不加,那么程序继续执行到循环内部 ,此时让 p 指向 next 程序就会奔溃。
程序代码:
#include <stdio.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node;
Node* getptr(Node* head, int pos)
{
Node *p = head;
if (p == NULL || pos == 0)
{
return head;
}
for (int i = 0; p && i < pos; i++)
{
p = p->next;
}
return p;
}
int main()
{
Node *head = NULL;
//...省略其他操作
Node *p = getpte(head, 3);
//...
return 0;
}
附图: