思路
这个也比较简单,和判断链表是否有环的思路类似,声明两个指针p1、p2指向链表首, 想让p2走k步,然后p1和p2一起走,直到p2到达链表尾部。
//查找链表倒数第k个元素
LinkNode *getLastK(LinkNode *head, int k){
int counter = k;
LinkNode *p1 = head, *p2 = head;
while(p1 != NULL && counter>0){
p1 = p1->next;
counter--;
}
if(counter != 0)
return NULL;
while(p1 != NULL){
p1 = p1->next;
p2 = p2->next;
}
return p2;
}
类似的一个问题
typedef struct linknode{
int data;
linknode *next;
} LinkNode;
//同尾单词,求单词共同后缀起始位置
//1.遍历统计单词长度la、lb
//2.取两指针,相隔|la - lb|
//3.同时对两链表遍历,并比较指针域的值
int getListLength(LinkNode *head){
int counter = 0;
while(head != NULL){
counter++;
head = head->next;
}
return counter;
}
LinkNode* getSameNode(LinkNode *head1, LinkNode *head2){
int la = getListLength(head1);
int lb = getListLength(head2);
if(la > lb){
int step = la-lb;
while(step > 0){
head1 = head1->next;
step--;
}
}else{
int step = lb-la;
while(step > 0){
head2 = head2->next;
step--;
}
}
while(head1 != head2){
head1 = head1->next;
head2 = head2->next;
}
return head1 == NULL ? NULL : head1;
}