当前位置:网站首页>Leetcode 19. delete the penultimate node of the linked list
Leetcode 19. delete the penultimate node of the linked list
2022-07-29 06:23:00 【Zhangchuming ZCM】
Power button | 19. Delete the last of the linked list N Nodes
Title screenshot

Method 1 : Two traversal
The first traversal calculates the length of the linked list to get the length length, And then use it k=length-n Get the location of the node to be deleted .
Second traversal , arrive k Use the location cur.next = cur.next.next Point the node pointer to the next node to be deleted . In this way, you have successfully deleted .
Considering that only one node needs to be deleted , Therefore, a node is set in front of the head node ans, Finally back to ans.next.
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length, cur = 0, head
while cur:
cur = cur.next
length += 1
ans = ListNode(0,head)
cur = ans
k = length - n
while k :
cur = cur.next
k -= 1
cur.next = cur.next.next
return ans.nextComplete test code
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length, cur = 0, head
while cur:
cur = cur.next
length += 1
ans = ListNode(0,head)
cur = ans
k = length-n
while k:
cur = cur.next
k -= 1
cur.next = cur.next.next
return ans.next
def create_linked_list(nums):
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for i in range(1, len(nums)):
cur.next = ListNode(nums[i])
cur = cur.next
return head
def print_linked_list(list_node):
if list_node is None:
return
cur = list_node
while cur:
print(cur.val, '->', end=' ')
cur = cur.next
print('null')
class main():
a = Solution()
nums = [1, 2, 51, 9, 26, 72, 4, 8]
n = 3
h = create_linked_list(nums)
b= a.removeNthFromEnd(head=h,n=n)
print(nums)
print(" Delete the last {0} Nodes , The value of this node is {1}".format(n, nums[len(nums)-n]))
print()
print(" The result of deleting the linked list is as follows :")
print_linked_list(b)
if __name__ == '__main__':
main()Method 2 : Stack
First store the entire linked list on the stack , Then use the characteristics of stack , Take the last element out of the stack . Then find the top element of the stack after it is out of the stack , This node is the previous node of the deleted node , Make this node point to the next node of the deleted node to successfully delete the specified node .
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ans = ListNode(0,head)
stack = list()
cur = ans
while cur:
stack.append(cur)
cur = cur.next
for i in range(n):
stack.pop()
prev = stack[-1]
prev.next = prev.next.next
return ans.nextMethod 3 : Double pointer
Use two pointers successively to traverse . There is no need to calculate the length of the linked list .
Because it is required to delete the penultimate list n Nodes , Then the first pointer is ahead of the second pointer n Nodes , Then traverse together , When the first 1 When a pointer reaches the end of the linked list , The second pointer just points to the penultimate n On a node .
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ans = ListNode(0,head)
first = head
for i in range(n):
first = first.next
second = ans
while first:
first = first.next
second = second.next
second.next = second.next.next
return ans.next边栏推荐
- Ml6 self study notes
- Leetcode 7. integer inversion
- 多线程和并发
- 【软件工程之美 - 专栏笔记】26 | 持续交付:如何做到随时发布新版本到生产环境?
- 给二维表添加时间序列索引
- 链表--------------------尾插法
- UE5 landscape 换算 Nanite 转换方式及不支持 配合 Lumen及Lumen开启 Dynamic Mesh 使用方法
- leetcode刷题笔记 763.划分字母区间(中等)
- [beauty of software engineering - column notes] 19 | as a programmer, you should have product awareness
- Eight sorts ----------- bubble sort
猜你喜欢

关于【链式前向星】的自学理解

Traditional model predictive control trajectory tracking - wavy trajectory (function package has been updated)
![[beauty of software engineering - column notes] 16 | how to write project documents?](/img/52/70d66230679abae6ce26d3477a22f6.png)
[beauty of software engineering - column notes] 16 | how to write project documents?

传统模型预测控制轨迹跟踪——波浪形轨迹(功能包已经更新)

【软件工程之美 - 专栏笔记】23 | 架构师:不想当架构师的程序员不是好程序员

LeetCode #344.反转字符串

Leetcode 13. Roman numeral to integer

LeetCode #83. 删除排序链表中的重复元素

Encapsulation - Super keyword

【软件工程之美 - 专栏笔记】25 | 有哪些方法可以提高开发效率?
随机推荐
Huawei cloud 14 days Hongmeng device development -day1 environment construction
计算机网络面试题
【软件工程之美 - 专栏笔记】22 | 如何为项目做好技术选型?
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
Leetcode 26. delete duplicates in the ordered array
数学建模心得
Eight sorts --------- quick sort
进程与进程的概念
JUC集合类不安全
SQLyog 安装和配置教程
LeetCode #977.有序数组的平方
【软件工程之美 - 专栏笔记】29 | 自动化测试:如何把Bug杀死在摇篮里?
leetcode刷题笔记 605. Can Place Flowers (Easy) 605.种花问题
LeetCode #344.反转字符串
【软件工程之美 - 专栏笔记】27 | 软件工程师的核心竞争力是什么?(上)
#7110 数字走向2 题解
LeetCode #83. 删除排序链表中的重复元素
【软件工程之美 - 专栏笔记】30 | 用好源代码管理工具,让你的协作更高效
传统模型预测控制轨迹跟踪——圆形轨迹(功能包已经更新)
传统模型预测控制轨迹跟踪——波浪形轨迹(功能包已经更新)