Zero basic learning java--single-chain surface test questions, ultra-detailed idea analysis

2. Reverse a singly linked list

How to reverse? The node does not change, change the node point, as shown in the figure

 Ideas and practices: only need to modify the point of each node, how to change the point of each node? Introduce a prev,

let cur.next=prev

prev = cur

cur = cur .next

 

3. Given a non-empty singly linked list with head node head, return the middle node of the linked list. If there are two intermediate nodes, return the second intermediate node

Ideas and practices: refer to two pointers, fast and slow pointers, fast and slow, fast takes two steps at a time, slow takes one step at a time, when fast reaches the end, slow is in the middle!

Introduce pointer fast and slow

 

 

4. Input a linked list and output the k-th node from the bottom of the linked list.

Thought, practice: refer to two pointers, fast and slow, first let fast go k-1 cloth, and then let slow and fast go together!

 code

5. Merge the two ascending linked lists into a new sorted linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.

First draw two linked lists, headA and headB

Practices, ideas, first of all, we apply for a virtual node (puppet node), the role: val12 and val13 whoever is smaller will be stringed in this virtual node.

 

 

 code

How to create two linked lists and print them

 result

6. Write code to divide the linked list into two parts based on a given value x, and all nodes less than x are sorted before nodes greater than or equal to x.

The idea of ​​this question is that we have two intervals, put one interval less than x, and one interval greater than x, and then put the two intervals together

 

 code

 

7. In a sorted linked list, there are duplicate nodes, please delete the duplicate nodes in the linked list, the duplicate nodes are not retained, and the pointer to the head of the linked list is returned.

code

Guess you like

Origin blog.csdn.net/Biteht/article/details/121517997