两个指针,相距为k(不是k-1!!)
注意:k的取值可能会很诡异,注意判断,见测试用例
#include <stdio.h>
typedef struct SLinkNode{
int value;
struct SLinkNode *next;
}LinkNode;
void addToLink(LinkNode **head, int i);
void printfLink(LinkNode *head);
LinkNode* lastK(LinkNode *head, int k);
int main(int argc, char *argv[])
{//测试用例:设链表长n,k=n,k=o, 0<k<n, k>n ,链表头传入NULL
int i;
LinkNode *head = NULL;
for(i=0 ; i<10 ; i++){
addToLink(&head, i);
}
printfLink(head);
LinkNode *result = lastK(NULL, 11);
if(result != NULL){
int v = result->value;
printf("%d\n", v );
}
return 0;
}
LinkNode* lastK(LinkNode *head, int k){
if(k <= 0)
return NULL;
LinkNode *first, *second;
first = head;
second = head;
int i = 0;
while(first != NULL){
first = first->next;
i++;
if(i == k)//!!!
break;
}
if(first == NULL)
return NULL;
while((first != NULL) && (second != NULL)){
first = first->next;
second = second->next;
}
return second;
}
void addToLink(LinkNode **head, int i){
LinkNode *t = (LinkNode*)malloc(sizeof(LinkNode));
t->value = i;
t->next = NULL;
if(t == NULL)
return;
if(*head == NULL)
*head = t;
else{
LinkNode *t2 = *head;
while(t2->next != NULL)
t2 = t2->next;
t2->next = t;
}
}
void printfLink(LinkNode *head){
while(head != NULL){
printf("%d\t", head->value);
head = head->next;
}
printf("\n");
}