采用的是设置两个指针,当两个指针距离为k-1时开始同时移动从而达到目的
#include<iostream>
#include<stdio.h>
using namespace std;
struct LNode{
int data;
LNode *next;
};//这个是定义了一个结构体,Lnode,里面有数据域data和指针域next。
int BackLocate(LNode L, int k){
LNode *p, *q;
int count = 0;
p = q = L.next;
while(q != NULL){//count为1,输出头节点后面的节点数据,即9;count为2,输出8;count为3,输出7;count为4,输出6,
count++;//count++先赋值再+1,++count先+1再赋值
printf("%d\n",count);
if(count > k)
p = p->next;
q = q->next;
printf("%d\n",count);
printf("%d\n",q->data);
printf("%d\n",p->data);
}
if(k > count) //当K大于链表长度时,返回-1
return -1;
return p->data;
}
int main(){
int a[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
LNode L, *r;
r = NULL;
for(int i=0; i<10; i++){ //尾插法建立链表
LNode *p;
p = new LNode;
p->data = a[i];
if(r == NULL){
L.next = p;
r = p;
}
else{
r->next = p;
r = p;
}
}
r->next = NULL;
printf("%d\n", BackLocate(L, 4));
}