题目描述
利用单链表表示一个整数序列,请实现一个时间复杂度为O(n)、空间复杂度为O(1)的算法,通过一趟遍历在单链表中确定倒数第k个结点。
编程要求
输入
多组数据,每组数据有三行,第一行为链表的长度n,第二行为链表的n个元素(元素之间用空格分隔),第三行为k。当n=0时输入结束。
输出
对于每组数据分别输出一行,输出每个链表的倒数第k个结点对应的数值。
c版本:
#include<stdio.h>
#include<stdlib.h>
//定义链表
typedef struct Node {
int val;
struct Node* next;
}node, * list;
list initlist() {
node* l = (node*)malloc(sizeof(node));
l->next = NULL;
l->val = -1;
return l;
}
list creat(int len) {
node* head = initlist();
// printf("%d ",head->val );
node* p = head;
// printf("%d ",p->val );
for (int i = 0; i < len; i++) {
node* s = (node*)malloc(sizeof(node));
scanf("%d", &s->val);
s->next = NULL;
p->next = s;
p = s;
}
return head;
}
void locate(node* A,int k) {
node* s = A->next;
node* p = A->next;
for(int i=0;i<k;i++){
p=p->next;
}
while(p!=NULL){
p=p->next;
s=s->next;
}
//return s;
A->next=s;
}
int main() {
int m = 0;
int count = 0;
int k = 0;
node** a = (node**)malloc(sizeof(node*) * 100);
int max[100]={0};
scanf("%d", &m);
for (int i = 0; m != 0; i++) {
a[i] = creat(m);
scanf("%d", &k);
locate(a[i],k);
count++;
scanf("%d", &m);
}
for (int i = 0; i <count; i++) {
node* s = a[i]->next;
printf("%d", s->val);
printf("\n");
}
}
C++版本:
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}LNode, * LinkList;
void CreateList_R(LinkList& L, int n)
{//后插法创建单链表
int x = 0;
LNode* p = L;
LNode* a;
while (n != 0) {
a = new LNode;
cin >> x;
a->data = x;
p->next=a;
p = p->next;
n--;
}
p->next = NULL;
}
void Search_k(LinkList L, int k)
{
LNode* p = L->next;
LNode* c = L->next;
int index = 0;
while (index != k) {
p = p->next;
index++;
}
while (p != NULL) {
p = p->next;
c = c->next;
}
if (c != NULL) {
cout << c->data << endl;
}
}
int main()
{
int n;
while (cin >> n)
{
if (n == 0) break;
LinkList L =new LNode;
L->next=NULL;
CreateList_R(L, n);
int k;
cin >> k;
Search_k(L, k);
}
return 0;
}