国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 建宁县| 偏关县| 特克斯县| 石河子市| 宝山区| 离岛区| 郎溪县| 泸溪县| 友谊县| 洛宁县| 施甸县| 青阳县| 全椒县| 梨树县| 丽水市| 卢湾区| 马公市| 施甸县| 磴口县| 思茅市| 云霄县| 年辖:市辖区| 宜都市| 赤峰市| 建始县| 泗阳县| 中山市| 长葛市| 易门县| 苏尼特左旗| 沛县| 施甸县| 安乡县| 防城港市| 绵竹市| 尼玛县| 泰顺县| 张家界市| 务川| 德格县| 汾阳市|