Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

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

Shulou Source: shulou.com Published: 2022-06-01 11:26:05 09月26日 Update

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!

Tags: Nodes points pointers questions number between elements content animation ideas more knowledge topics presentations mobile practical effective successful learning next code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Redmi macOS Linux