热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在单链表中仅提供指向要删除的节点的指针,如何删除它?

在单链表中仅提供指向要删除的节点的指针,如何删除它?原文:htt

在单链表中仅提供指向要删除的节点的指针,如何删除它?

原文:https://www.geeksforgeeks.org/in-a-linked-list-given-only-a-pointer-to-a-node-to-be-deleted-in-a-singly-linked-list-how-do-you-delete-it/

简单解决方案是遍历链表,直到找到要删除的节点。 但是此解决方案需要指向头节点的指针,该指针与问题陈述相矛盾。

快速解决方案是将数据从下一个节点复制到要删除的节点,然后删除下一个节点。 像这样:

struct Node *temp = node_ptr->next;
node_ptr->data = temp->data;
node_ptr->next = temp->next;
free(temp);

下面是上述代码的实现:

C++

// C++ program to del the node
// in which only a single pointer
// is known pointing to that node
#include
#include
using namespace std;
/* Link list node */
class Node {
public:
    int data;
    Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();
    /* put in the data */
    new_node->data = new_data;
    /* link the old list off the new node */
    new_node->next = (*head_ref);
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
void printList(Node* head)
{
    Node* temp = head;
    while (temp != NULL) {
        cout <data <<" ";
        temp = temp->next;
    }
}
void deleteNode(Node* node_ptr)
{
    // If the node to be deleted is the 
    // last node of linked list
    if (node_ptr->next == NULL)
    {
        free(node_ptr);
        // this will simply make the node_ptr NULL.
        return;
    }
    // if node to be deleted is the first or 
    // any node in between the linked list.
    Node* temp = node_ptr->next;
    node_ptr->data = temp->data;
    node_ptr->next = temp->next;
    free(temp);
}
// Driver code
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
    /* Use push() to construct below list
    1->12->1->4->1 */
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
    cout <<"Before deleting \n";
    printList(head);
    /* I m deleting the head itself.
        You can check for more cases */
    deleteNode(head);
    cout <<"\nAfter deleting \n";
    printList(head);
    return 0;
}
// This code is contributed by rathbhupendra

C

// C++ program to del the node
// in which only a single pointer
// is known pointing to that node
#include
#include
#include
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    /* put in the data  */
    new_node->data = new_data;
    /* link the old list off the new node */
    new_node->next = (*head_ref);
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
void printList(struct Node* head)
{
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
}
void deleteNode(struct Node* node_ptr)
{
    // If the node to be deleted is the last 
    // node of linked list
    if (node_ptr->next == NULL)
    {
        free(node_ptr);
        // this will simply make the node_ptr NULL.
        return;
    }
    struct Node* temp = node_ptr->next;
    node_ptr->data = temp->data;
    node_ptr->next = temp->next;
    free(temp);
}
// Driver code 
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    /* Use push() to construct below list
    1->12->1->4->1  */
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
    printf("\n Before deleting \n");
    printList(head);
    /* I m deleting the head itself.
        You can check for more cases */
    deleteNode(head);
    printf("\n After deleting \n");
    printList(head);
    getchar();
}

Java

// Java program to del the node in 
// which only a single pointer is 
// known pointing to that node
class LinkedList {
    static Node head;
    static class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
    void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
    void deleteNode(Node node)
    {
        Node temp = node.next;
        node.data = temp.data;
        node.next = temp.next;
        System.gc();
    }
    // Driver code
    public static void main(String[] args)
    {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(12);
        list.head.next.next = new Node(1);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(1);
        System.out.println("Before Deleting ");
        list.printList(head);
        /* I m deleting the head itself.
         You can check for more cases */
        list.deleteNode(head);
        System.out.println("");
        System.out.println("After deleting ");
        list.printList(head);
    }
}
// This code has been contributed by Mayank Jaiswal

Python3

# A python3 program to delete
# the node in which only a single pointer
# is known pointing to that node
# Linked list node
class Node():
    def __init__(self):
        self.data = None
        self.next = None
# Given a reference (pointer to pointer)
# to the head of a list and an int,
# push a new node on the front of the list
def push(head_ref, new_data):
    # allocate node
    new_node = Node()
    # put in the data
    new_node.data = new_data
    # link the old list off the new node
    new_node.next = head_ref
    # move the head to point to the new node
    head_ref = new_node
    return head_ref
def printList(head):
    temp = head
    while(temp != None):
        print(temp.data, end=' ')
        temp = temp.next
def deleteNode(node_ptr):
    temp = node_ptr.next
    node_ptr.data = temp.data
    node_ptr.next = temp.next
# Driver code
if __name__ == '__main__':
    # Start with the empty list
    head = None
    # Use push() to construct below list
    # 1->12->1->4->1
    head = push(head, 1)
    head = push(head, 4)
    head = push(head, 1)
    head = push(head, 12)
    head = push(head, 1)
    print("Before deleting ")
    printList(head)
    # I'm deleting the head itself.
    # You can check for more cases
    deleteNode(head)
    print("\nAfter deleting")
    printList(head)
# This code is contributed by Yashyasvi Agarwal

C

// C# program to del the node in
// which only a single pointer is
// known pointing to that node
using System;
public class LinkedList {
    Node head;
    public class Node {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
    void printList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }
    void deleteNode(Node node)
    {
        Node temp = node.next;
        node.data = temp.data;
        node.next = temp.next;
    }
    // Driver code
    public static void Main()
    {
        LinkedList list = new LinkedList();
        list.head = new Node(1);
        list.head.next = new Node(12);
        list.head.next.next = new Node(1);
        list.head.next.next.next = new Node(4);
        list.head.next.next.next.next = new Node(1);
        Console.WriteLine("Before Deleting ");
        list.printList(list.head);
        /* I m deleting the head itself.
        You can check for more cases */
        list.deleteNode(list.head);
        Console.WriteLine("");
        Console.WriteLine("After deleting ");
        list.printList(list.head);
    }
}
/* This code contributed by PrinciRaj1992 */

输出

Before deleting
1 12 1 4 1
After deleting
12 1 4 1

为了使该解决方案有效,我们可以将末端节点标记为虚拟节点。 但是使用此函数的程序/函数也应进行修改。

对于双链表,请尝试解决此问题。


推荐阅读
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 李逍遥寻找仙药的迷阵之旅
    本文讲述了少年李逍遥为了救治婶婶的病情,前往仙灵岛寻找仙药的故事。他需要穿越一个由M×N个方格组成的迷阵,有些方格内有怪物,有些方格是安全的。李逍遥需要避开有怪物的方格,并经过最少的方格,找到仙药。在寻找的过程中,他还会遇到神秘人物。本文提供了一个迷阵样例及李逍遥找到仙药的路线。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • 本文介绍了为什么要使用多进程处理TCP服务端,多进程的好处包括可靠性高和处理大量数据时速度快。然而,多进程不能共享进程空间,因此有一些变量不能共享。文章还提供了使用多进程实现TCP服务端的代码,并对代码进行了详细注释。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • 本文介绍了使用Python解析C语言结构体的方法,包括定义基本类型和结构体类型的字典,并提供了一个示例代码,展示了如何解析C语言结构体。 ... [详细]
author-avatar
_ZY寶貝_
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有