您的位置:首页 > 理论基础 > 数据结构算法

【数据结构与算法】:倒数第K个数

2016-07-24 21:57 197 查看
这个题很简单,倒数第K个数,先顺序遍历一边,找出链表中一共有多少个数(假设为Num个),然后再次遍历,其中第num-k个数就是要找的

两函数如下:

int GetLength(struct node *head){
int count = 0;
struct node *temp = head;
while(temp!=NULL){
count++;
temp = temp->next;
}
return count;
}

int getReverseK(struct node *head,int k){
struct node *temp = head;
int num = GetLength(head);
for(int i=0;i<num-k;i++){
temp = temp->next;
}
cout<<"倒数第K个数是"<<temp->data<<endl;
return 0;
}


非常的简单,一下子就能够明白了

在这里我要给一个彩蛋,我这里给出一种方法2,方法2是用两个链表,保持K个距离即可

void getReverseKonlyOnce(struct node *head,int k){
struct node *temp1 = head;
struct node *temp2 = head;
for(int i=0;i<k;i++){
temp1 = temp1->next;
}
while(temp1!=NULL){
temp1 = temp1->next;
temp2 = temp2->next;
}
cout<<"倒数第K个数是"<<temp2->data;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: