習題3.5 求鏈表的倒數第m個元素 (20分)
請設計時間和空間上都儘可能高效的算法,在不改變鏈表的前提下,求鏈式存儲的線性表的倒數第m(>0)個元素。
函數接口定義:
ElementType Find( List L, int m );
其中List
結構定義如下:
typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存儲結點數據 */
PtrToNode Next; /* 指向下一個結點的指針 */
};
typedef PtrToNode List; /* 定義單鏈表類型 */
L
是給定的帶頭結點的單鏈表;函數Find
要將L
的倒數第m
個元素返回,並不改變原鏈表。如果這樣的元素不存在,則返回一個錯誤標誌ERROR
。
裁判測試程序樣例:
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 細節在此不表 */
void Print( List L ); /* 細節在此不表 */
ElementType Find( List L, int m );
int main()
{
List L;
int m;
L = Read();
scanf("%d", &m);
printf("%d\n", Find(L,m));
Print(L);
return 0;
}
/* 你的代碼將被嵌在這裏 */
輸入樣例:
5
1 2 4 5 6
3
輸出樣例:
4
1 2 4 5 6
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
#define N 20
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read();
void Print( List L );
ElementType Find( List L, int m );
ElementType Length( List L);
int main()
{
List L;
int m;
L = Read();
scanf("%d", &m);
printf("%d\n", Find(L,m));
Print(L);
return 0;
}
ElementType Find( List L, int m ){
int i=0,n, findWhich;
List h,p;
h=L;
p=h->Next;
n = Length(L);
findWhich = n-m+1;/* 將倒數轉換爲正數第幾個數*/
while(p){
i++;
if(i==findWhich)
break;
p=p->Next;
}
return p->Data;
}
ElementType Length( List L){
int len=0;
List h,p;
h=L;
p=h->Next;
while(p){
len++;
p=p->Next;
}
return len;
}
List Read(){
int a[N],i,n;
List h,p,q;
scanf("%d", &n);
for(i=0;i<n;i++)
a[i]=2*i+1;
for(i=0;i<n;i++)
printf("%d ", a[i]);
printf("\n");
h=(List)malloc(sizeof(struct Node));
h->Next=NULL;
p=q=h;
for(i=0;i<n;i++){
q=(List)malloc(sizeof(struct Node));
q->Data=a[i];
q->Next=NULL;
p->Next=q;
p=q;
}
p->Next=NULL;
return h;
}
void Print( List L ){
List p;
p=L->Next;
while(p){
printf("%d ", p->Data);
p=p->Next;
}
printf("\n");
}