【经典算法】: 求链表中倒数第K个结点
2016-07-17 22:11
316 查看
链表中倒数第K个节点的求法
方法有两个:
1,先算出来链表中有多少个节点,假设为count个,然后顺序遍历
找到count-k个时就可以截至
2,先对整个链表反序,然后倒过来找第K个即可
下面给出第一种方法:
上面是函数,然后下面是完整的程序:
方法有两个:
1,先算出来链表中有多少个节点,假设为count个,然后顺序遍历
找到count-k个时就可以截至
2,先对整个链表反序,然后倒过来找第K个即可
下面给出第一种方法:
static void GetKNumber(struct node** head_ref,int k){ int count = 0,temp=0; struct node* head = *head_ref; struct node* head_trail = *head_ref; while(head!=NULL){ count++; head = head->next; } while(head_trail!=NULL){ temp++; if(temp-1==count-k){ cout<<"the k data is"<<head_trail->data<<endl; } head_trail = head_trail->next; } }
上面是函数,然后下面是完整的程序:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node{
int data;
struct node* next;
};
void push(struct node** head_ref,int new_data){
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
static void reverse(struct node** head_ref){ //用于翻转,把所有的对应关系都反过来
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while(current!=NULL){
next = current->next;
current->next = prev; //倒过来指
prev = current;
current = next; //用来将循环往后拖
}
*head_ref = prev; //代表着最后一个
}
//链表中倒数第K个节点
static void GetKNumber(struct node** head_ref,int k){ int count = 0,temp=0; struct node* head = *head_ref; struct node* head_trail = *head_ref; while(head!=NULL){ count++; head = head->next; } while(head_trail!=NULL){ temp++; if(temp-1==count-k){ cout<<"the k data is"<<head_trail->data<<endl; } head_trail = head_trail->next; } }
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
int main(){
struct node* head = NULL;
push(&head,20);
push(&head,4);
push(&head,15);
push(&head,85);
push(&head,60);
push(&head,100);
printList(head);
GetKNumber(&head,2);
reverse(&head);
cout<<endl<<"翻转后的结果"<<endl;
printList(head);
return 0;
}
相关文章推荐
- 用户态与内核态的切换与区别
- Matlab R2010a和vs 2010混合编程
- CentOS下SNMP的安装与使用
- html5 的拖放
- The requested resource (/) is not available
- [Linux/Ubuntu] vi/vim 使用方法讲解
- NYOJ 24 素数距离问题
- Python中的编码(encode)与解码(decode)
- 代码故事:汉德的救赎
- JAVA学习总结二十五
- sublime 2221
- 从零开始学_JavaScript_系列(24)——查看对象属性,合并数组
- how to iterate each tableview cells
- 代码故事:汉德的救赎
- 如何在 Linux 上录制你的终端操作
- fibonacci 通项式
- GSON的使用介绍
- ccnu_2016_summer_week1(1)
- Vue.jsbrowserify项目模板
- android button的使用