資料結構與演算法(4) 查詢鍊錶中倒數第n個結點

2021-07-29 05:10:46 字數 1852 閱讀 4153

題目:查詢鍊錶中倒數第n個結點

解析:這個題目有三種解法,分別如下

/**

* 找到鍊錶中倒數第n個結點

*@param n 倒數結點位置

*@return 倒數第n個結點

*/public

static listnode getreciprocalnode1(listnode headnode, int n)

// 判斷鍊錶個數是否夠n個

if (n > length)

/** 方法一:根據位置獲取倒數第n個結點

* 總共length個結點,倒數第n個就等於正著數的(length-n+1)個結點

*/listnode currentnode = getnodebyposition(headnode, length - n + 1);

return currentnode;

}

方法二:每次都從當前結點掃瞄鍊錶中剩餘的結點個數

這裡採用乙個笨的方法,從第乙個開始乙個乙個判斷,每次都從當前結點掃瞄鍊錶中剩餘的結點個數

/**

* 找到鍊錶中倒數第n個結點

*@param n 倒數結點位置

*@return 倒數第n個結點

*/public

static listnode getreciprocalnode2(listnode headnode, int n)

// 判斷鍊錶個數是否夠n個

if (n > length)

/*

* 方法二:每次都從當前結點掃瞄鍊錶中剩餘的結點個數

* 這裡採用乙個笨的方法,從第乙個開始乙個乙個判斷,每次都從當前結點掃瞄鍊錶中剩餘的結點個數

*/listnode currentnode = headnode;

while(length > n)

return currentnode;

}

方法三:

使用兩個指標ptemp和pnth。首先,兩個指標都指向鍊錶的頭結點。

先使ptemp移動n次後,pnth才開始移動。此時兩個指標一起移動,

當ptemp指標移動到鍊錶的尾部,也就是ptemp指向鍊錶的最後乙個結點。

此時pnth所指向的結點就是所要求的倒數第n個結點。

/**

* 找到鍊錶中倒數第n個結點

*@param n 倒數結點位置

*@return 倒數第n個結點

*/public

static listnode getreciprocalnode3(listnode headnode, int n)

// 判斷鍊錶個數是否夠n個

if (n > length)

/** 方法三:

* 使用兩個指標ptemp和pnth。首先,兩個指標都指向鍊錶的頭結點。

* 先使ptemp移動n次後,pnth才開始移動。此時兩個指標一起移動,

* 當ptemp指標移動到鍊錶的尾部,也就是ptemp指向鍊錶的最後乙個結點。

* 此時pnth所指向的結點就是所要求的倒數第n個結點。

*/listnode ptemp = headnode;

listnode pnth = headnode;

// 使ptemp移動n次

for (int i = 0; i < n; i++)

}// ptemp和pnth兩個指標一起移動

while (ptemp != null)

// 返回結果

return pnth;

}

目前為止,方法三是乙個很有效的解決方案。

資料結構與演算法 鍊錶

題目 合併兩個已經排序好的鍊錶 非遞迴和遞迴兩種 方法1 cpp view plain copy print color 000000 合併鍊錶.cpp 定義控制台應用程式的入口點。include stdafx.h include using namespace std struct listnod...

資料結構與演算法 鍊錶

在講述鍊錶之前讓我們對資料結構進行乙個簡單的回顧 我們知道,資料結構指的是描述實際問題中各個資料項節點之間的前後邏輯結構關係,即要麼是線性結構 即某一資料項的前繼節點和後繼節點有且只有乙個 要麼是非線性結構 即某一資料節點的前驅或者後繼節點不止乙個 在確定了實際資料項的資料結構之後,我們要採用某種儲...

資料結構與演算法 鍊錶

反轉鍊錶 def reverse head q none p heap while p temp p.next p.next q q pp temp return p判斷鍊錶環 def meetingnode head if not head return slow head fast head.n...