#include<iostream>
#define ElemType int
using namespace std;
typedef struct Node {
ElemType data;
struct Node *next;
};
void Create(Node *&l) { //尾插法
int x;
l->next = NULL; //头结点
Node *s,*r = l; //r为表尾指针
cin >> x;
while (x != -1) {
s = new Node;
s->data = x;
r->next = s;
r = s;
cin >> x;
}
r->next = NULL;
}
void Print(Node *&l) { //输出链表中的数据
Node *p = l->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void Delete(Node *&l) { //单链表的删除操作
Node *p = l;
Node *q = l->next; //保存后继指针,防止断链
while (p!= NULL ) {
delete p;
p = q;
if (q != NULL) {
q = q->next;
}
}
}
int Search_K(Node *&l,int k) { //查询倒数第k个数
Node *p = l->next, *q = l->next;
int count = 0; //计数
while (p != NULL) {
if (count < k) {
count++;
}
else {
q = q->next;
}
p = p->next;
}
if (count < k) {
return 0;
}
else {
cout << q->data << endl;
return 1;
}
}
int main() {
Node *l = new Node; //新建结点,并且创建指针
Create(l);
Search_K(l, 4);
Print(l);
Delete(l); //释放内存
system("pause");
return 0;
}
/*
4 5 6 7 8 9 10 11 12 -1
*/