当前位置:网站首页>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边栏推荐
- Dynamic planning summary
- Number theory: proof that the maximum number that px+py cannot represent is pq-p-q
- 八大排序-----------快速排序
- Ml8 self study notes LDA principle formula derivation
- 【软件工程之美 - 专栏笔记】30 | 用好源代码管理工具,让你的协作更高效
- [beauty of software engineering - column notes] 16 | how to write project documents?
- 计算机网络面试题
- 从头安装MYSQL(MYSQL安装文档-解压版)
- 位运算学习笔记
- 【Leetcode刷题】数组1——双指针
猜你喜欢

LeetCode #14. 最长公共前缀

Leetcode 26. delete duplicates in the ordered array

ML10 self study notes SVM

markdown与Typora

MySql-面试题

JUC concurrent knowledge points

LeetCode #876.链表的中间结点

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

Pit avoidance: about the interconnection of two hc-05 master-slave integrated Bluetooth modules, there is no connection problem
![[beauty of software engineering - column notes] 13 | how to break the rhythm of writing code during daytime meetings and overtime?](/img/e2/56234084d0cfad6906f9e84212182a.png)
[beauty of software engineering - column notes] 13 | how to break the rhythm of writing code during daytime meetings and overtime?
随机推荐
【软件工程之美 - 专栏笔记】23 | 架构师:不想当架构师的程序员不是好程序员
Huawei cloud 14 day Hongmeng device development -day2 compilation framework
循环链表和双向链表
利用云打码来破解登录遇到验证码的问题
UE5 光影基础 阴影全解析 锯齿阴影解决方案 Lumen
leetcode刷题笔记 763.划分字母区间(中等)
crawl笔记
Ml9 self study notes
抽象类以及接口
【软件工程之美 - 专栏笔记】“一问一答”第2期 | 30个软件开发常见问题解决策略
ML10 self study notes SVM
Leetcode 13. Roman numeral to integer
唯美girls
2022 spring move - core technology FPGA development post pen test question (original question and experience)
TB6600+stm32F407测试
【软件工程之美 - 专栏笔记】22 | 如何为项目做好技术选型?
关于【链式前向星】的自学理解
#7110 数字走向2 题解
八大排序-----------------堆排序
抽象封装继承多态