【经典算法】: 求链表中倒数第K个结点
来源:互联网 发布:怎么在淘宝上买种子 编辑:程序博客网 时间:2024/05/01 18:37
链表中倒数第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;}
0 0
- 【经典算法】: 求链表中倒数第K个结点
- 【算法】求链表中倒数第K个结点
- 求链表中倒数第k个结点
- 求链表中倒数第k个结点
- 求链表中倒数第k个结点
- 求链表中倒数第k个结点
- 求链表中倒数第K个结点
- 求链表中倒数第k个结点
- 求链表中倒数第k个结点
- 面试经典题目:链表中倒数第k个结点
- 算法题9 查找链表中倒数第k个结点
- 算法学习五---输出链表中倒数第k个结点
- 面试算法(十四)链表中倒数第k个结点
- 算法题:求链表倒数第K个结点
- 算法(一)求链表中的倒数第K 个结点
- 每天一个算法之链表中倒数第K个结点
- 算法题目---链表中倒数第k个结点
- 算法-获取链表中倒数第k个结点
- 异步任务之AsyncTask实现<一>
- [Linux/Ubuntu] vi/vim 使用方法讲解
- APP开发实战99-Android的内部存储(Internal Storage)
- Latex生成PDF文件中字体无法嵌入
- Matlab R2010a和vs 2010混合编程
- 【经典算法】: 求链表中倒数第K个结点
- Python 3.5 import easygui invalid syntax
- Java-算法之选择排序
- 腾讯云配置密钥使用putty登录
- poj 1572 kmp
- diff patch 打补丁
- 从零开始学_JavaScript_系列(25)——dojo(10)摧毁一个widget
- 读过不错的电子书籍
- JAVA学习总结二十六