The penultimate node in the Java output linked list

Problem description

Input a linked list and output the penultimate node in the linked list. (the tail node is the last to last)

Nodes are defined as follows:

Idea 1:

First traverse the linked list and calculate its length; Then it is calculated that the penultimate node is the positive length - K + 1 Finally, traverse the linked list to find the node time complexity O (2n), which needs to traverse the linked list twice

The code is as follows:

Idea 2:

Look forward to traversing the linked list only once. Set two pointers, one to the first node and the second to the k-th node. Then the two pointers move backward synchronously. When the second pointer points to the tail node, the first pointer points to the penultimate node

code:

Idea 3:

Reverse the linked list, then the original problem becomes the k-th node of the positive number. However, this changes the original linked list and is not more efficient than idea 2

Linked list inversion: refer to Java language code example for implementing inverted linked list

The above is all about the penultimate node in the Java output linked list. Interested friends can continue to refer to: Java programming to delete duplicate nodes in the linked list, solution ideas and source code sharing, Java programming to print linked list code examples from end to end, and other related topics on this site. If there are deficiencies, you are welcome to leave a message and point out that the editor must correct them in time, Give you a better reading experience and help. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>