請設計時間和空間上都盡可能高效的演算法,在不改變鍊錶的前提下,求鏈式儲存的線性表的倒數第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()
/* 你的**將被嵌在這裡 */
5
1 2 4 5 6
3
4
1 2 4 5 6
演算法思路:
先求出來表長len,然後倒數第m個元素,就從頭遍歷單鏈表,直到遍歷到第len-m個結點,然後這個元素就是它下乙個結點。
**
elementtype find( list l, int m )
if(m > len)
return error;
p = l; // p指標重新指向頭結點
int i = 0; // 計數器
while(p->next && i < len-m)
return p->next->data;
}
習題3 5 求鍊錶的倒數第m個元素 20分
elementtype find list l,int m 其中list結構定義如下 typedef struct node ptrtonode struct node typedef ptrtonode list 定義單鏈表型別 l是給定的帶頭結點的單鏈表 函式find要將l的倒數第m個元素返回,...
求鍊錶的倒數第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,在初始...