The difficult problem about a linked list makes me doubt my IQ

Broken thoughts:

As a rookie who has a headache when he sees the data structure, today he tried to practice a linked list topic on a whim.

I thought about various selection structures to guide the direction of the program. After reading the answer, I found that such complicated steps were not needed at all.

Although it is a small topic, I still reflect on why there is such an obvious difference in thinking, as follows.

Topic - remove linked list elements:

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点

Topic source: LeetCode 203.


problem solving process

我的解法

First my code:

# class Node:

#     def __init__(self,data,next) -> None:
#         self.data = data
#         self.next = next

""""生成的链表带有data为None的头结点"""

def delete_val_linklist(self,val):
        """移除单链表元素""" 
        h = self.head  # h始终是当前观测的结点
        while h.next:
            if h.next.data!=val :  # 如果当前h结点的data不是val,就后移h
                p = h.next
                h = p
            else:           #  如果当前h结点的data是val,就进行细化操作
                p = h.next  
                if p.next:
                    h.next = p.next
                    if p.next.data != val:   
                        h = p.next
                    else:
                        p = h.next
                else:
                    h.next = None

Here, in order to solve the situation that the target node is ① the first node after the head node, ② is the last node, ③ encounters several consecutive target nodes, etc., all possible situations have been considered into the if selection structure .

After a second review, it was found that the most important step in the code - the transfer of the h node, and the definition of invalid variables, such as the " " in the first if, can actually be solved p = h.next ; h = pwith h = h.nextclear efficient.

简洁解法

    def delete_val_linklist_1(self,val):
        h = self.head
        while h.next:
            if h.next.data == val:
                h.next = h.next.next
            else:
                h = h.next

I lost. .

If one is the target point, jump back two steps, if not, just jump one step, and know which node's next is None and which one is not.


Some reflections:

I feel that I am still afraid of the data structure. I always think that the solution will be more complicated, and in order to completely clarify the connection between the nodes of the linked list, each step has been refined, so the writing is not concise enough.

On the other hand, it may be related to your own personality, and it is easy to think about various minor details or special situations, but fail to grasp the main contradiction.


Supongo que te gusta

Origin blog.csdn.net/weixin_50593821/article/details/125446620
Recomendado
Clasificación