#include <iostream>
#include <assert.h>
#include <queue>
using namespace std;
struct Node{
int data;
Node* next;
};
void createList(Node* &list,int value){
if(list==NULL){
list=new Node;
list->data=value;
list->next=NULL;
return;
}
createList(list->next,value);
}
void printList(Node* list){
Node* p=list;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void findKthReverse(Node* list,int k){
if(list==NULL||k<=0)
return;
Node *p1,*p2;
p1=p2=list;
int skip=0;
while(skip<k-1){
p2=p2->next;
if(p2==NULL)
return;
skip++;
}
while(p2->next!=NULL){
p1=p1->next;
p2=p2->next;
}
cout<<p1->data<<endl;
}
void main(){
Node* list=NULL;
for(int i=0;i<10;i++)
createList(list,i+1);
printList(list);
findKthReverse(list,1);
findKthReverse(list,2);
findKthReverse(list,10);
system("pause");
}
查找链表中倒数第k个结点
最新推荐文章于 2023-04-14 15:43:27 发布