定义结构体
#include//printf #include //malloc #include //strlen typedef int Elemtype; //数据元素的类型 //定义数据节点 typedef struct node { Elemtype data; //数据域:保存数据本身用的 struct node *next; //指针域:用来保存关系用的,保存下一个数据节点的地址 }Node;
Node *Last_K_Node(Node *list,int k)
{
//定义两个哨兵,第一个哨兵先走k步,然后第一个和第二个一起走,当第一个
//指向NULL时,第二个就会指向倒数第k个节点
Node *p1 = list;
Node *p2 = list;
while(k--)
{
p1 = p1->next;
}
while(p1)
{
p1 = p1->next;
p2 = p2->next;
}
return p2;
}
void Print_Linklist(Node *list)
{
Node *p = list;
while(p){
printf("%d ",p->data);
p = p->next;
}
putchar('n');
}
int main()
{
//返回链表中倒数第k个节点的值(k由你自己指定)
Node *list = Create_Linklist();//list指向创建出来的有序单链表的首节点
Print_Linklist(list);
Elemtype k;
printf("请输入要获取的是倒数第几个元素:n");
scanf("%d",&k);
Node *p = Last_K_Node(list,k);
printf("%dn",p->data);
return 0;
}
**运行结果**
大家有什么问题可以私信我哦!



