- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Node in a Linked List in Python
Suppose we have a linked list with few elements. Our task is to write a function that will delete the given node from the list. So if the list is like 1 → 3 → 5 → 7 → 9, and after deleting 3, it will be 1 → 5 → 7 → 9.
Consider we have the pointer ‘node’ to point that node to be deleted, we have to perform these operations to delete the node −
- node.val = node.next.val
- node.next = node.next.next
Example (Python)
Let us see the following implementation to get a better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution(object): def deleteNode(self, node, data): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ while node.val is not data: node = node.next node.val = node.next.val node.next = node.next.next head = make_list([1,3,5,7,9]) ob1 = Solution() ob1.deleteNode(head, 3) print_list(head)
Input
linked_list = [1,3,5,7,9] data = 3
Output
[1, 5, 7, 9, ]
- Related Articles
- Delete a node in a Doubly Linked List in C++
- Delete a Linked List node at a given position in C++
- Delete a Node from linked list without head pointer in C++
- Delete a Doubly Linked List node at a given position in C++
- Python program to delete a node from the end of the Circular Linked List
- Python program to delete a node from the middle of the Circular Linked List
- Golang Program to delete the first node from a linked list.
- Golang Program to delete the last node from a linked list.
- C++ Program to Delete the First Node in a given Singly Linked List
- Python program to delete a new node from the beginning of the doubly linked list
- Python program to delete a new node from the end of the doubly linked list
- Python program to delete a new node from the middle of the doubly linked list
- Delete a tail node from the given singly Linked List using C++
- Golang Program to delete the node after the Kth node (K is not in the linked list).
- Linked List Random Node in C++

Advertisements