請設計時間和空間上都盡可能高效的演算法,在不改變鍊錶的前提下,求鏈式儲存的線性表的倒數第m(>0)個元素。
elementtype find
( list l,
int m )
;
其中list
結構定義如下:
typedef
struct node *ptrtonode;
struct node
;typedef ptrtonode list;
/* 定義單鏈表型別 */
l
是給定的帶頭結點的單鏈表;函式find
要將l
的倒數第m
個元素返回,並不改變原鍊錶。如果這樣的元素不存在,則返回乙個錯誤標誌error
。
#include
#include
#define error -1
typedef
int elementtype;
typedef
struct node *ptrtonode;
struct node
;typedef ptrtonode list;
list read()
;/* 細節在此不表 */
void
print
( list l )
;/* 細節在此不表 */
elementtype find
( list l,
int m )
;int
main()
/* 你的**將被嵌在這裡 */
512
4563
412
456
#include
#include
#define error -1
typedef
int elementtype;
typedef
struct node *ptrtonode;
struct node
;typedef ptrtonode list;
list read()
;/* 細節在此不表 */
void
print
( list l )
;/* 細節在此不表 */
elementtype find
( list l,
int m )
;int
main()
/* 你的**將被嵌在這裡 */
/* * @description : 建立乙個使用者定義的鍊錶
* @param : 無
* @return : 新的的鍊錶
*/list read()
//安全起見,尾指標為空
p->next =
null;}
return head;}/*
* @description : 列印鍊錶
* @param -l : 需要列印的鍊錶
* @return : 無
*/void
print
( list l )
else
}printf
("\n");
}/** @description : 查詢函式
* @param -l : 需要查詢的鍊錶
* @param -m : 第m個元素
* @return : 返回找到的元素
* 不存在返回錯誤
*/elementtype find
( list l,
int m )
if(m > len)
else
return p-
>next-
>data;
}}
該方法不是最優解,耗時26ms,如果大佬有更好的方法,請多多指教! 求鍊錶的倒數第m個元素
習題3.5 求鍊錶的倒數第m個元素 20分 請設計時間和空間上都盡可能高效的演算法,在不改變鍊錶的前提下,求鏈式儲存的線性表的倒數第m 0 0 個元素。elementtype find list l,int m 其中list結構定義如下 typedef struct node ptrtonode s...
求鍊錶的倒數第m個元素
方法一 先遍歷一次鍊錶,得到長度n,在從頭遍歷找到第n m 1個元素。elementtype find list l,int m if m n m的位置不合法 int i 1 p l for i n m 1 i p p next return p data 方法二 定義兩個指標變數p1,p2,在初始...
求鍊錶的倒數第m個元素
請設計時間和空間上都盡可能高效的演算法,在不改變鍊錶的前提下,求鏈式儲存的線性表的倒數第m 0 個元素。函式介面定義 elementtype find list l,int m 其中list結構定義如下 typedef struct node ptrtonode struct node typede...