1
\$\begingroup\$

I am working on an easy LinkedList basic operation problem on Remove Linked List Elements - LeetCode

  1. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

My solution:

The 3 nodes: prev_node(prev), current_node(cur), next_node(nxt)

change prev.next from current_node to next_node

prev

cur = prev.next

nxt = prev.next.next

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        #relation: prev.next = nxt to replace cur
        prev = head
        if prev == None: return head
        if prev.next == None: #cur == None:
            if prev.next.val == 6:
                prev.next = None
            return head 

        while prev.next != None: #cur !=None
            if prev.next.val == 6: #if cur.val == 6
                nxt = prev.next.next
                prev.next = nxt
                prev = prev.next #advance to traverse
        return head

The solution:

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        #relation: prev.next = nxt to replace cur
        dummy = prev = ListNode(0)
        prev.next = head 

        while prev != None and prev.next != None: #cur !=None
            if prev.next.val == val: #if cur.val == val
                nxt = prev.next.next
                prev.next = nxt
            else:
                prev = prev.next #advance to traverse
        return dummy.next

However, it reported Time Limit ExceededError.

I assume that problem is not performance but mistakes in my implementation which I don't find.

What's the problem?

\$\endgroup\$

closed as off-topic by 200_success, 1201ProgramAlarm, AJNeufeld, яүυк, pacmaninbw Apr 23 at 10:55

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – 200_success, 1201ProgramAlarm, AJNeufeld, яүυк, pacmaninbw
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    \$\begingroup\$ I believe that your solution is actually incorrect, not just slow. \$\endgroup\$ – 200_success Apr 23 at 0:56
  • \$\begingroup\$ thank you.I find the problem. I am surprised than you are so responsible to read almost every post. @200_success. Thank you. \$\endgroup\$ – Alice Apr 23 at 1:02