Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to delete the penultimate node of a linked list by List

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to delete the penultimate node of the linked list by List". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Problem: delete the penultimate node of the linked list

Title

Given a linked list, delete the penultimate node of the linked list and return the header node of the linked list.

Example:

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

When the penultimate node is deleted, the linked list becomes 1-> 2-> 3-> 5

Description:

The given n guarantee is valid.

Advanced:

Can you try to do it with a scan?

Problem-solving ideas

Adopting double traversal can certainly solve the problem, but the problem requires us to traverse and solve the problem at once, then we have to diverge our thinking.

We can imagine that if double pointers p and Q are set, when Q points to the end of the NULL,p and the number of elements separated by Q is n, then deleting the next pointer to p completes the requirement.

Set the virtual node dummyHead to point to head

Set double pointers p and Q, which initially point to the virtual node dummyHead

Move Q until the number of elements separated by p and Q is n

Move p and Q at the same time until Q points to NULL

Point the next node of p to the next node

Animation demonstration

The animation GIF is a little big. Please wait a little while to load and display ^ _ ^.

This is the end of the reference code "how to delete the penultimate node of the linked list by List". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report