C语言之算法与数据结构练习篇-寻找带头结点单链表的倒数第K个位置上的数
算法思想:设置两个工作指针p,q同时指向头指针;其中p先走k步,然后p,q在同时走当p遍历到单链表的尾部时,q对应的就是单链表的倒数第K个位置上的数
完整代码如下
#include<stdio.h>
#include<stdlib.h>
//定义单链表结构
typedef struct node{
int value;
struct node *next;
}Node;
//定义头指针
typedef struct list{
Node *head;
}List;
//输入数据
void initList(List *L){
//定义头结点
Node *first;
first=(Node *)malloc(sizeof(Node));
if(!first){
printf("wrong!\n");
}
Node *tail;
L->head=first;
tail=L->head;
first->next=NULL;
first->value=0;
for(int i=0;i<=10;i++){
Node *new=(Node *)malloc(sizeof(Node));
if(!new){
printf("wrong2!\n");
}
new->value=i;
tail->next=new;
new->next=NULL;
tail=new;
}
}
//查找第k个数
int find_k_number(List L,int k){
int count=0;
Node *p=L.head;
Node *q=L.head;
p=p->next;
//找到第k-1个位置
while(q&&count<k){
q=q->next;
count++;
}
if(q==NULL) {
printf("find position wrong\n");
return 0;
}
while(q->next!=NULL){
p=p->next;
q=q->next;
}
printf("%d\n",p->value);
return 1;
}
int main(){
List l;
initList(&l);
int find_or_not=find_k_number(l,2);
return 0;
}
最后的最后,技术小白第一次写如有错误欢迎指正