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

首頁 > 學院 > 開發設計 > 正文

[Leetcode] 19. Remove Nth Node From End of List

2019-11-08 20:19:08
字體:
來源:轉載
供稿:網友

PRoblem:

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.

Idea: 1. 用空間換時間方法。從head開始遍歷單向鏈表,把每一項放入數組中(此時存放的都是鏈表節點的引用)。遍歷完畢后,計算數組的大小(即單向鏈表的長度),然后用總長度減去n,可得需要移除的項的下標。然后直接訪問數組中該下標,修改對應以及臨近節點的值即可。 2. n ahead。設置兩個游標,其中fast游標比slow游標快n個節點。當fast游標到達鏈表末端時,slow游標所指的節點就是待刪節點。 3. 遞歸法。先通過遞歸調用index()函數找到末節點的值,然后把倒數第n個節點之前的節點值往后挪一個位置:“node.next.val = node.val”以下是摘抄自作者:

Value-Shifting - AC in 64 ms

My first solution is “cheating” a little. Instead of really removing the nth node, I remove the nth value. I recursively determine the indexes (counting from back), then shift the values for all indexes larger than n, and then always drop the head.

Solution: 1.

class Solution(object): def removeNthFromEnd(self, head, n): nodelist = [] if head == None: return tmpnode = head while tmpnode.next != None: nodelist.append(tmpnode) tmpnode = tmpnode.next nodelist.append(tmpnode) lenlist = len(nodelist) targetindex = lenlist - n if targetindex == 0: if lenlist == 1: return None else: head = nodelist[1] elif targetindex == lenlist - 1: nodelist[lenlist-2].next = None else: nodelist[targetindex-1].next = nodelist[targetindex+1] return head2. class Solution: def removeNthFromEnd(self, head, n): fast = slow = head for _ in range(n): fast = fast.next if not fast: return head.next while fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return head

3.

class Solution: def removeNthFromEnd(self, head, n): def index(node): if not node: return 0 i = index(node.next) + 1 if i > n: node.next.val = node.val return i index(head) return head.next
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宿迁市| 东城区| 京山县| 柯坪县| 泾川县| 邯郸市| 武城县| 务川| 伊宁市| 延安市| 高雄县| 府谷县| 崇仁县| 辽宁省| 祥云县| 乌兰浩特市| 崇阳县| 江永县| 布拖县| 嘉定区| 巫溪县| 夏邑县| 孝感市| 苏尼特左旗| 扎赉特旗| 峨边| 眉山市| 信宜市| 云林县| 财经| 彭阳县| 利津县| 全椒县| 邢台市| 乌拉特前旗| 玉龙| 徐州市| 垦利县| 大姚县| 威海市| 衡山县|