找单链表中倒数第K个元素
2016-10-27 23:00
239 查看
//找单链表中倒数第K个元素,不保证存在,找不到,相关函数返回-1 //思路: //第一个游标在第一个元素处,另一个在第一个元素处开始右移,看看能不能使两个游标形成 最后一个与倒数第K个 的状态 //若能,两个游标同时右移,直到右边游标到达末尾,这时第一个游标处就是所求元素处 //若不能,返回-1 #include <stdio.h> #include <stdlib.h> #define k 4 struct node{ int data; struct node *next; }; struct node* Insert(struct node*head,int element)//相同的,插到后面 { //findprevious and insert element after the position found; struct node* t=head; while(t->next!=NULL&&t->next->data<=element) t=t->next; struct node *p; p=(struct node*)malloc(sizeof(struct node)); p->data=element; p->next=t->next; t->next=p; return head; }; int FindKthFromEnd(struct node* head) { struct node *temp,*t; int count; temp=head->next; t=head->next; count=1; while(count<=k&&temp){ temp=temp->next; count++; } if(count<k) return -1; while(temp){ t=t->next; temp=temp->next; } return t->data; } int main(){ //申请表头 struct node *head; head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; //插入元素 for(int i=1;i<=10;i++) head=Insert(head,i);//以10为例 int number=FindKthFromEnd(head); printf("%d\n",number); return; }
//C++实现 #include <cstdio> #include <iostream> #include <vector> using namespace std; vector <int> array; int main(){ int k,number; int len; cin>>k; while(scanf("%d",&number)!=EOF&&number>=0) array.push_back(number); len=array.size(); if(k<=0||len<k) cout<<"NULL\n"; else cout<<array[len-k]<<'\n'; return 0; }
相关文章推荐
- 在链表中查找倒数第k个元素
- 输出单向链表的倒数第K个元素
- 【每日一题】CareerCup2.2 寻找链表中倒数第K个元素
- 【学习点滴-数据结构-单链表】 求单链表的中间元素和倒数第k个元素
- 算法分析-查找单链表中的倒数第k个元素和中间元素
- 剑指offer --反向输出链表与输出链表的倒数第k个元素
- 查找单链表中倒数第k个元素
- 取单链表倒数第k个元素
- 链表中倒数第k个元素
- 查找链表的倒数第k个元素
- Q:链表的倒数第K个元素
- 找出一个无环单链表里面的倒数第K个元素,时间复杂度为O(n)
- Interview----链表的倒数第K个元素
- 每天一算法(输出链表倒数第k个元素)
- Interview----链表的倒数第K个元素
- 【剑指offer】打印链表倒数第k个元素
- 寻找单链表中倒数第k个元素
- 链表中倒数第K个元素,
- 查找一个单向链表中倒数第K个元素
- 链表的倒数第k个元素(mark)