国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

每日一道算法題——Remove Nth Node From End of List

2019-11-08 03:12:08
字體:
供稿:網(wǎng)友

去掉倒數(shù)第n的節(jié)點

題目

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list

becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass.

分析

題目說明了n總是合法的,并且建議我們用一次遍歷完成。題目中給出的節(jié)點類如下:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */

這是寫節(jié)點可以構(gòu)成一個單向鏈表,所以無法回頭!

算法

采用兩個引用,一快一慢,中間的間隔為給出的n,所以當(dāng)快的那個到了末尾,那么慢的那個的下一個元素就指向了要去除的元素了。 雖然看起來挺簡單,但是實現(xiàn)起來并不容易,邊界條件還是比較多的,但是我寫完之后看了下面那個代碼,我就發(fā)現(xiàn),真是太機智了!

代碼

public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); ListNode slow = start, fast = start; slow.next = head; //Move fast in front so that the gap between slow and fast becomes n for(int i=1; i<=n+1; i++) { fast = fast.next; } //Move fast to the end, maintaining the gap while(fast != null) { slow = slow.next; fast = fast.next; } //Skip the desired node slow.next = slow.next.next; return start.next; }}

他在開始新建了一個節(jié)點,所以避免了很多不必要的特殊條件的判斷。大家可以自己嘗試一下,然后自己輸入一些數(shù)據(jù)驗證一下。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 香港 | 来安县| 贵南县| 绿春县| 岑巩县| 淳安县| 融水| 邓州市| 甘泉县| 辽宁省| 永清县| 安溪县| 余干县| 通渭县| 澄城县| 琼中| 五河县| 宝清县| 桐乡市| 汽车| 新兴县| 全椒县| 北碚区| 定州市| 台前县| 高雄市| 介休市| 砀山县| 鄂托克前旗| 澄城县| 宜兰县| 剑阁县| 吐鲁番市| 宣化县| 绥中县| 绥化市| 明溪县| 昆山市| 大丰市| 道孚县| 宜州市|