Skip to content

Instantly share code, notes, and snippets.

@adarsh0806
Created May 31, 2016 17:35
Show Gist options
  • Save adarsh0806/02d8e1d54d510294e75dfbc0d9bd7059 to your computer and use it in GitHub Desktop.
Save adarsh0806/02d8e1d54d510294e75dfbc0d9bd7059 to your computer and use it in GitHub Desktop.
delete_first
def delete_first(self):
deleted = self.head
if self.head:
self.head = self.head.next
deleted.next = None
return deleted
@AlirezaShk
Copy link

My implementation:

def delete_first(self):
        "Delete the first (head) element in the LinkedList as return it"
        node = self.head
        try: self.head = self.head.next
        except AttributeError: pass
        finally: return node

This is according to the official best practices of Python, adhering to the EAFP. Basically claiming that it's computationally faster (in no-error cases) to use try/except instead of if/else statements.

@Kingkobi01
Copy link

My Implementation:

 def delete_first(self):
        "Delete the first (head) element in the LinkedList as return it"
        if self.head is None:
            return None
            
        current = self.head
        self.head = self.head.next
        
        return current

@demoreon
Copy link

I hope this helps

        "Delete the first (head) element in the LinkedList as return it"
        temp = self.head
        self.head = temp.next if temp else None
        return temp```

@Tadei18
Copy link

Tadei18 commented Jul 13, 2023

delete
Hope this helps

@LekeneCedric
Copy link

LekeneCedric commented Nov 29, 2023

def delete_first(self):
        deleted_element = None
        if self.head is not None:
            deleted_element = self.head
            deleted_element.next = None
            if self.head.next is not None:
                self.head = self.head.next
            else:
                self.head = None
        return deleted_element

@israel-oye
Copy link

Compared to most solution, I think I was too explicit

def delete_first(self):
        if self.head:
            old_head = self.head
            if self.head.next:
                new_head = self.head.next
                self.head = new_head
                old_head.next = None
            else:
                self.head = None
            return old_head
        return None

@LekeneCedric
Copy link

LekeneCedric commented Jan 18, 2024 via email

@GrvExplorer
Copy link

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment